Adding a comma after every two digits to String.Format

I tried to format the number 173910234.23into something like 17,39,10,234.23. Here, only the first thousand separators after three digits. But after that all the delimiters ( ,) are after two digits. I tried the following -

double d = 173910234.23;
Console.WriteLine(string.Format("{0:#,##,##,###.00}", d));

but it gives a semicolon after every three digits, 173,910,234.23

How to achieve format 17,39,10,234.23with string.Format?

+4
source share
2 answers

Numeric groups are defined by a property NumberGroupSizes NumberFormatInfo. So change it accordingly and just use the format specifier N.

double d = 173910234.23;
var culture = new CultureInfo("en-us", true)
{
    NumberFormat =
    {
        NumberGroupSizes = new int[] { 3, 2 }
    }
};
Console.WriteLine(d.ToString("N", culture));

Displays

17,39,10,234.23


@Rawling @Hamlet, . OP , - .

+8
string output = null;    
string num = Number.ToString();
for(int i = 0; i < num.Length; ++i)
 {
        switch(i)
        case 2:
        case 4:
        case 6:
            output += ",".ToString() + num[i].ToString(); 
        break;
        default:
            output += num[i].ToString(); 
        break:
 }

, , (, 0)

0

All Articles