删除尾随零

2023-09-02 10:17:29 作者:不帅不用钱

我有一个集合作为

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

However, if the number is a Decimal and the precision specifier is omitted, fixed-point notation is always used and trailing zeros are preserved

更新 康拉德 pointed出的评论:

观察下面0.000001值。 G29格式present他们在最短的方式,因此将切换到该指数符号。 的String.Format({0:G29},decimal.Parse(0.00000001,System.Globalization.CultureInfo.GetCultureInfo(EN-US)))将给予1E-08作为结果。

Watch out for values like 0.000001. G29 format will present them in the shortest possible way so it will switch to the exponential notation. string.Format("{0:G29}", decimal.Parse("0.00000001",System.Globalization.CultureInfo.GetCultureInfo("en-US"))) will give "1E-08" as the result.

相关推荐