【问题标题】:Converting number to comma separated values将数字转换为逗号分隔值
【发布时间】:2013-06-03 06:24:51
【问题描述】:

我需要将数字转换成逗号分隔的格式以显示在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。

【问题讨论】:

标签: c# string.format


【解决方案1】:

我想您可以根据自己的需要创建自定义数字格式信息来做到这一点

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

【讨论】:

  • 非常感谢!这节省了一天
  • 我没有得到小数点。如何获得像'10,200.15'这样的小数
【解决方案2】:

这里有一个与你类似的帖子add commas in thousands place for a number

这是对我来说完美的解决方案

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

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

【讨论】:

    【解决方案3】:

    如果你想要独一无二并做你不必做的额外工作,这里是我为整数创建的一个函数,你可以在任何你想要的间隔放置逗号,只需将 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;
        }
    

    【讨论】:

      【解决方案4】:

      你试过了吗:

      ToString("#,##0.00")
      

      【讨论】:

        【解决方案5】:

        快速而肮脏的方式:

        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】:

          一个简单的解决方案是将格式传递给 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
          

          希望这会有所帮助,

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2015-05-20
            • 1970-01-01
            • 2021-09-27
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-02-08
            • 1970-01-01
            相关资源
            最近更新 更多