Remove trailing zeros

后端 未结 18 1233
天命终不由人
天命终不由人 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 11:54

    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();
    

提交回复
热议问题