Remove trailing zeros

Zo Has picture Zo Has · Dec 24, 2010 · Viewed 163.8k times · Source

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

Thomas Materna picture Thomas Materna · Nov 2, 2011

I ran into the same problem but in a case where I do not have control of the output to string, which was taken care of by a library. After looking into details in the implementation of the Decimal type (see http://msdn.microsoft.com/en-us/library/system.decimal.getbits.aspx), I came up with a neat trick (here as an extension method):

public static decimal Normalize(this decimal value)
{
    return value/1.000000000000000000000000000000000m;
}

The exponent part of the decimal is reduced to just what is needed. Calling ToString() on the output decimal will write the number without any trailing 0. E.g.

1.200m.Normalize().ToString();