String.Format 一个整数以使用不带小数位的千位分隔符或小整数前导 0
愚蠢的问题,我想格式化一个整数,以便它与 1000 的分隔符 (,) 一起出现,但也没有小数位,也没有前导 0。
到目前为止我的尝试是:
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
我想要的输出是:
5 5,000
有什么东西吗很明显我失踪了?
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.
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这对我有用。
This worked for me.
试试这个:-
Try this:-
0
表示放置属于此处的数字,或者[前导/尾随]零[以使事物对齐等]。编辑:您肯定会希望将 1 作为模式中的最后一位数字,否则零值将呈现为空字符串#
意味着不要将任何内容放入输出中,除非此处有有效数字。编辑(感谢@eulerfx):
0
而不是#
(正如我最初的那样),因为零值否则会呈现为零长度字符串。0
in 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.EDIT (thanks @eulerfx):
0
rather than a#
(as I initially had it) as a value of zero would otherwise be rendered as a zero-length string.尝试
Try
随着 C# 6.0 中字符串插值的介绍,有一种更好/更好的方法来使用
$
并使用{变量/值[,alignment][:formatString]}
。With the introduction String interpolation in C# 6.0, there is a better/nicer way to work with strings using
$
and string formatting using{variable/value[,alignment][:formatString]}
.这也有效:
40000.ToString("#,#")
This also works:
40000.ToString("#,#")