将数字转换为逗号分隔值

3

我需要将数字转换为逗号分隔格式,以在 C# 中显示。

例如:

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

如何在 C# 中实现这个功能?

我尝试了以下代码:

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

但它无法处理lakhs


你尝试过使用 ToString("N0"); 吗? - V4Vendetta
可能重复 - https://dev59.com/iHVD5IYBdhLWcg3wDXF3(如果可行的话,我最喜欢这种方法: {0:#,#}) - Sayse
可能是 C# 中的 String.Format 的重复问题。 - taocp
6个回答

7
我想你可以通过创建一个符合你需求的自定义数字格式来实现这一点。
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

如果仅针对数字,您也可以这样做:
nfo.NumberGroupSeparator = ",";
nfo.NumberGroupSizes = new int[] { 3, 2 };

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

非常感谢!这拯救了今天。 - ShinyJos
我在这里没有得到小数点。如何获得像“10,200.15”这样的小数点? - Rohan Sampat

3
这是一个与你类似的帖子,讨论的内容是如何在数字的千位加逗号,以下是相关链接:add commas in thousands place for a number。这里有一个对我非常有效的解决方案。
     String.Format("{0:n}", 1234);

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

2

如果你想要独特并且愿意多做一些不必要的工作,这里有一个我为整数数字创建的函数。你可以在任何间隔处放置逗号,只需将3放置在每千位上即可,或者你也可以选择2、6或其他你喜欢的数字。

             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;
    }

1

你尝试过了吗:

ToString("#,##0.00")

0

快速而粗略的方法:

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);

0
一个简单的解决方案是将格式传递到 ToString() 方法中:
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

希望这能有所帮助,

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接