问题描述
我有一个集合作为
2.4200
2.0044
2.0000
我要像
2.42
2.0044
2
我试着用的String.Format
,但它返回 2.0000
键,将其设置为 N0
舍入其它值。
I tried with String.Format
, but it returns 2.0000
and setting it to N0
rounds the other values as well.
推荐答案
这难道不是如此简单,如果输入的是一个字符串?您可以使用其中的一个:
Is it not as simple as this, if the input IS a string? You can use one of these:
string.Format("{0:G29}", decimal.Parse("2.0044"))
decimal.Parse("2.0044").ToString("G29")
2.0m.ToString("G29")
这应该适用于所有的输入。
This should work for all input.
更新查看标准数字格式我'已经有明确设置precision说明29的文档明确规定:
Update Check out the Standard Numeric Formats I've had to explicitly set the precision specifier to 29 as the docs clearly state:
但是,如果数字是一个小数和precision说明省略,定点符号总是使用和尾随零是preserved
更新 康拉德 pointed出的评论:
观察下面0.000001值。 G29格式present他们在最短的方式,因此将切换到该指数符号。 的String.Format({0:G29},decimal.Parse(0.00000001,System.Globalization.CultureInfo.GetCultureInfo(EN-US)))
将给予1E-08作为结果。
这篇关于删除尾随零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!