C# String.Format 一个整数以使用没有小数位的千位分隔符或小整数前导 0

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1666346/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 19:50:00  来源:igfitidea点击:

String.Format an integer to use a thousands separator without decimal places or leading 0 for small integers

c#string-formatting

提问by Justin

Silly question, I want to format an integer so that it appears with the 1000's separator (,), but also without decimal places and without a leading 0.

愚蠢的问题,我想格式化一个整数,使其以 1000 的分隔符 (,) 出现,但也没有小数位和前导 0。

My attempts so far have been:

到目前为止,我的尝试是:

String.Format("{0} {1}", 5, 5000);            // 5 5000
String.Format("{0:n} {1:n}", 5, 5000);        // 5.00 5,000.00
String.Format("{0:0,0} {1:0,0}", 5, 5000);    // 05 5,000

The output I'm after is:

我追求的输出是:

5 5,000

Is there something obvious that I'm missing?

有什么明显的东西我失踪了吗?

采纳答案by Richard Friend

This worked for me.

这对我有用。

String.Format("{0:#,0} {1:#,0}", 5, 5000); // 5 5,000

回答by Ruben Bartelink

String.Format("{0:#,0} {1:#,0}", 5, 5000); // "5 5,000"
  • 0in a format string means put the digit that belongs here, or else a [leading/trailing] zero [to make things align, etc.]. EDIT: You'll definitely want one as the last digit in the pattern, or a zero value will be rendered as an empty String
  • #means don't put anything into the output unless there's a significant digit here.
  • 0在格式字符串中意味着把属于这里的数字,或者[前导/尾随]零[使事情对齐等]。编辑:您肯定需要一个作为模式中的最后一位数字,否则零值将呈现为空字符串
  • #意味着不要在输出中放入任何东西,除非这里有一个有效数字。

EDIT (thanks @eulerfx):

编辑(感谢@eulerfx):

  • the last portion needs to be a 0rather than a #(as I initially had it) as a value of zero would otherwise be rendered as a zero-length string.
  • 最后一部分需要是 a0而不是 a #(正如我最初拥有的那样),否则零值将呈现为零长度字符串。

回答by Anax

Try

尝试

String.Format("{0:#,#}", 4000);

回答by ZafarYousafi

Try this:-

尝试这个:-

String.Format("{0:n0}",5000) // 5,000
String.Format("{0:n0}",5) // 5
String.Format("{0:n0}",0) // 0