Remove trailing zeros

后端 未结 18 1218
天命终不由人
天命终不由人 2020-11-22 11:26

I have some fields returned by a collection as

2.4200
2.0044
2.0000

I want results like

2.42
2.0044
2

I t

18条回答
  •  余生分开走
    2020-11-22 12:04

    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.

    Update Check out the Standard Numeric Formats I've had to explicitly set the precision specifier to 29 as the docs clearly state:

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

    Update Konrad pointed out in the comments:

    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.

提交回复
热议问题