Reputation: 4358
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
?
Upvotes: 4
Views: 1552
Reputation: 73442
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..
Upvotes: 8
Reputation: 538
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:
}
If you want to use a different number, replace the numbers with the positions of the numbers where you want to insert the comma before (remember the first character of a string has the position of 0)
Upvotes: 0