c# 如何将 double 格式设置为字符串并仅在必要时显示十进制数字?

标签 c# string-formatting

我在 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");

Digit placeholder

Replaces the pound sign with the corresponding digit if one is present; otherwise, no digit appears in the result string.

Zero placeholder

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/

相关文章:

c# - VS 2008 中的 "Unable to start debugging"消息

c# - 如何查找在wpf中选中的动态创建的CheckBox

c# - 设置注册表值时出现 NullReferenceException

.net - 显示引号 "

java - 在Java中用零填充

c# - 无法从程序集 Simple.OData.Client.V3.Adapter 加载 OData 适配器

c# - 使用自定义 JsonConverter 来改变对象部分的序列化

swift - 在小数点分隔符前后都打印 Double 和两位数字

string - 如何转义Python 3 '' '字符串中的字符?

c# - 如何格式化包含数字和字符的字符串