【问题标题】:How do I format a number with commas?如何用逗号格式化数字?
【发布时间】:2010-10-16 13:00:05
【问题描述】:
int a = 10000000;
a.ToString();

如何进行输出?

10,000,000

【问题讨论】:

标签: c# numbers tostring


【解决方案1】:

试试N0 没有小数部分:

string formatted = a.ToString("N0"); // 10,000,000

【讨论】:

  • 有没有办法使用 a.ToString("#"); 来做到这一点?在我的情况下,我需要该值为零时为空白,但我也需要逗号 - 或者我应该像 a.ToString("#,###,###,###,###,# ##,###")?
  • 您可能需要执行 if{}else{} 块来处理零。
  • @cms 如何实现这个10,24,78,000
【解决方案2】:

你也可以做String.Format:

int x = 100000;
string y = string.Empty;
y = string.Format("{0:#,##0.##}", x); 
//Will output: 100,000

如果有小数,同样的代码会输出2位小数:

double x = 100000.2333;
string y = string.Empty;
y = string.Format("{0:#,##0.##}", x); 
//Will output: 100,000.23

用逗号代替小数点:

double x = 100000.2333;
string y = string.Empty;
y = string.Format(System.Globalization.CultureInfo.GetCultureInfo("de-DE"), "{0:#,##0.##}", x);

【讨论】:

  • 如果小数分隔符是逗号呢?
【解决方案3】:

a.ToString("N0")

另请参阅:Standard Numeric Formatting Strings from MSDN

【讨论】:

    【解决方案4】:

    更简单的 String.Format 选项:

    int a = 10000000;
    String.Format("{0:n0}", a); //10,000,000
    

    【讨论】:

      【解决方案5】:

      a.tostring("00,000,000")

      【讨论】:

      • 我想你把 // 从字面上看,我认为 OP 的意思是把它写成注释代码。
      • 你可以试试 a = "10,000,000" ;)
      猜你喜欢
      • 1970-01-01
      • 2014-05-31
      • 2020-12-18
      • 2017-12-09
      • 2011-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多