Arturo Martinez Arturo Martinez - 1 month ago 20
C# Question

First two values of list to currency

i have a list of strings filled with decimal's in wich only the first two values of it must be currency while the others have to take the decimals out

This is the list of strings

2451.37
1678.00
12.00
90.00
10.00


i need to make the output to be:

$2,451.37
$1,678.00
12
90
10


i have tryed this :

<h4 class="semi-bold">
@if (haveDataDay)
{
@valueDateDay.ToString(valueDateDay % 1 == 0 ? "N0" : "C2") }

else
{ @this.FP("lbl.loader.nodata") }
</h4>
</div>


But this only makes currency the values that have decimals other than ".00 " but sometimes my list has the first two values with ".00" in wich case they dont get the currency change

how can i archive this?

Answer

You can convert your strings to doubles, then use built-in formatting tools. There are .NET methods to handle both currency and rounding/digit truncation.

using System;
using System.Collections.Generic;
using System.Globalization;

namespace CurrencyFormatting_StackOverflow
{
    class Program
    {
        static void Main(string[] args)
        {
            var strings = new List<string>()
            {
                "2451.37",
                "1678.00",
                "12.00",
                "90.00",
                "10.00"
            };
            FormatStrings(strings);
            string display = string.Join("\n", strings);
            Console.WriteLine(display);
            /*
            * $2,451.37
            * $1,678.00
            * 12
            * 90
            * 10
            */
            Console.ReadKey();
        }

        private static void FormatStrings(List<string> strings)
        {
            int index = 0;
            for (; index < 2; index++)
            {
                string s = strings[index];
                double d = double.Parse(s);
                string currency = d.ToString("C2", CultureInfo.CreateSpecificCulture("en-US"));
                strings[index] = currency;
            }
            for (; index < strings.Count; index++)
            {
                string s = strings[index];
                double d = double.Parse(s);
                double rounded = Math.Round(d, 2);
                strings[index] = rounded + "";
            }
        }
    }
}