Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding comma after each two digits in String.Format

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

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

but it gives output with comma after every three digits, 173,910,234.23

How can I achieve the format 17,39,10,234.23 using string.Format?

like image 455
th1rdey3 Avatar asked Feb 14 '23 14:02

th1rdey3


1 Answers

Number groups are defined by NumberGroupSizes property of NumberFormatInfo. So modify it accordingly and just use N format specifier.

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

This outputs

17,39,10,234.23


Thanks @Rawling and @Hamlet, for shedding light on this. Now OP gets expected output and me too learned something..

like image 71
Sriram Sakthivel Avatar answered Feb 24 '23 09:02

Sriram Sakthivel