Zo Has Zo Has - 3 months ago 34
C# Question

Remove trailing zeros

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 tried with
String.Format
, but it returns
2.0000
and setting it to
N0
rounds the other values as well.

Answer

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.