在较长的数字之间添加逗号

时间:2013-06-05 13:18:33

标签: c#

我试图自动将逗号放在长号之间,但到目前为止还没有成功。我可能犯了一个非常简单的错误,但到目前为止我无法弄明白。这是我目前的代码,但出于某种原因,我得到123456789作为输出。

    string s = "123456789";
    string.Format("{0:#,###0}", s);
    MessageBox.Show(s); // Needs to output 123,456,789

5 个答案:

答案 0 :(得分:1)

试试这个:

string value = string.Format("{0:#,###0}", 123456789);

在您的代码中,您缺少格式字符串中的初始{,然后数字格式选项适用于数字,而s是字符串。
您可以将字符串转换为int.Parse的数字:

int s = int.Parse("123456789");
string value = string.Format("{0:#,###0}", 123456789);
MessageBox.Show(value); 

答案 1 :(得分:1)

这应该有用(您需要传递String.Format()一个数字,而不是另一个String):

Int32 i = 123456789;
String s = String.Format("{0:#,###0}", i);
MessageBox.Show(s);

但请考虑您正在使用的格式字符串......有更清晰的选项,正如其他人所建议的那样。

答案 2 :(得分:1)

var input = 123456789;

// these two lines amount to the same thing
Console.WriteLine(input.ToString("N0"));
Console.WriteLine(string.Format("{0:N0}", input));

根据您的问题,如果您需要以string

开头
var stringInput = "123456789";
var input = int.Parse(stringInput);

// these two lines amount to the same thing
Console.WriteLine(input.ToString("N0"));
Console.WriteLine(string.Format("{0:N0}", input));

在解析/格式化时,您可能还需要考虑文化。查看带有IFormatProvider

的重载

答案 3 :(得分:0)

查看MSDN上的数字格式信息:Standard Numeric Format Strings,或者选择自定义格式字符串:Custom Numeric Format Strings

对于自定义数字格式:

  

“,”字符既可以作为组分隔符,也可以作为数字缩放说明符。

double value = 1234567890;
Console.WriteLine(value.ToString("#,#", CultureInfo.InvariantCulture));
// Displays 1,234,567,890      
Console.WriteLine(value.ToString("#,##0,,", CultureInfo.InvariantCulture));
// Displays 1,235   

答案 4 :(得分:0)

您的代码存在很多错误,因此很难描述每个细节。

看看这个例子:

namespace ConsoleApplication1
{
  using System;

  public class Program
  {
    public static void Main()
    {
      const int Number = 123456789;
      var formatted = string.Format("{0:#,###0}", Number);

      Console.WriteLine(formatted);
      Console.ReadLine();
    }
  }
}
相关问题