Converting Number to Comma Separated Values

本小妞迷上赌 提交于 2019-12-11 01:56:02

问题


I Need to convert numbers in comma separated format to display in C#.

For Example:

1000 to 1,000
45000 to 45,000
150000 to 1,50,000
21545000 to 2,15,45,000

How to achieve this in C#?

I tried the below code:

int number = 1000;
number.ToString("#,##0");

But it is not working for lakhs.


回答1:


I guess you can do this by creating a custom number format info for your needs

NumberFormatInfo nfo = new NumberFormatInfo();
nfo.CurrencyGroupSeparator = ",";
// you are interested in this part of controlling the group sizes
nfo.CurrencyGroupSizes = new int[] { 3, 2 };
nfo.CurrencySymbol = "";

Console.WriteLine(15000000.ToString("c0", nfo)); // prints 1,50,00,000

if specifically only for numbers then you could also do

nfo.NumberGroupSeparator = ",";
nfo.NumberGroupSizes = new int[] { 3, 2 };

Console.WriteLine(15000000.ToString("N0", nfo));



回答2:


Here's a similar thread to yours add commas in thousands place for a number

and here's the solution that worked perfectly with me

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

     String.Format("{0:n0}", 9876); // no decimals



回答3:


If you want to be unique and do extra work that you don't have to here is a function I created for integer numbers you can place commas at whatever interval you want, just put 3 for a comma for each thousandths or you could alternatively do 2 or 6 or whatever you like.

             public static string CommaInt(int Number,int Comma)
    {
     string IntegerNumber = Number.ToString();
     string output="";
     int q = IntegerNumber.Length % Comma;
     int x = q==0?Comma:q;
     int i = -1;
     foreach (char y in IntegerNumber)
     {
             i++;
             if (i == x) output += "," + y;
             else if (i > Comma && (i-x) % Comma == 0) output += "," + y;
             else output += y;

     }
     return output;
    }



回答4:


Have you tried:

ToString("#,##0.00")



回答5:


Quick and dirty way:

Int32 number = 123456789;
String temp = String.Format(new CultureInfo("en-IN"), "{0:C0}", number);
//The above line will give Rs. 12,34,56,789. Remove the currency symbol
String indianFormatNumber = temp.Substring(3);



回答6:


An easy solution would be to pass a format into the ToString() method:

string format = "$#,##0.00;-$#,##0.00;Zero";
   decimal positiveMoney = 24508975.94m;
   decimal negativeMoney = -34.78m;
   decimal zeroMoney = 0m;
   positiveMoney.ToString(format);  //will return $24,508,975.94
   negativeMoney.ToString(format);  //will return -$34.78 
   zeroMoney.ToString(format);      //will return Zero

Hope this helps,



来源:https://stackoverflow.com/questions/16891030/converting-number-to-comma-separated-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!