简体   繁体   中英

Add commas in decimal to string

I want to add a comma in the decimal to string conversion like

For

decimal number = 1000000000.000;

it should give

string str = 1,00,00,00,000.00

You can achieve this by using the correct CultureInfo :

decimal input = 1000000000.0000m;
CultureInfo ci = new CultureInfo("hi-IN");
string output = string.Format(ci,"{0:#,#.00}",input);

By the way: following CultureInfos produce the correct output:

hi,bn,pa,gu,or,ta,te,kn,ml,as,mr,sa,kok,si,ne,
hi-IN,bn-IN,pa-IN,gu-IN,or-IN,ta-IN,te-IN,kn-IN,
ml-IN,as-IN,mr-IN,sa-IN,kok-IN,si-LK,ne-NP,bn-BD,en-IN

Of course, you can use some predefined culture , but I would like to introduce this way, with NumberGroupSizes to specify whatever format you want:

CultureInfo ci = new CultureInfo("en-US");
ci.NumberFormat.NumberGroupSizes = new int[] { 3, 2 };
Thread.CurrentThread.CurrentCulture = ci;
Console.WriteLine("{0:#,#.00}", 12345678.12);
//output 
1,23,45,678.12
ci.NumberFormat.NumberGroupSizes = new int[] {4, 2};
//output
12,34,5678.12
//....

Here is a example:

http://msdn.microsoft.com/en-us/library/fzeeb5cd.aspx

specifier = "#,#.00#;(#,#.00#)";
Console.WriteLine("{0}: {1}", specifier, (value*-1).ToString(specifier));
// Displays:    #,#.00#;(#,#.00#): (16,325.62)

你可以这样做,

String.Format("{0:#,###0}", 0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM