我在 StackOverFlow 中发现了这个问题,但它并没有解决我的问题。 How do I format a double to a string and only show decimal digits when necessary?
Weight
0.500
18.000
430.000
通过上述 url 中的解决方案,我的结果以这种形式显示:
Weight
0.5
18
430
我的问题是小数位,我想用 3 位显示小数位,如下所示:
Weight
0.500
18
430
最佳答案
您可以在点 之后使用数字占位符
以字符串格式。#
和零占位符 0
。
string num = d % 1 == 0 ? d.ToString(".###") : d.ToString(".000");
Replaces the pound sign with the corresponding digit if one is present; otherwise, no digit appears in the result string.
places the zero with the corresponding digit if one is present; otherwise, zero appears in the result string.
这篇 msdn 文章 Custom Numeric Format字符串解释了如何格式化数字。
关于c# 如何将 double 格式设置为字符串并仅在必要时显示十进制数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24485245/