Best way to display decimal without trailing zeroes

前端 未结 14 1422
终归单人心
终归单人心 2020-11-27 04:49

Is there a display formatter that will output decimals as these string representations in c# without doing any rounding?

// decimal -> string

20 -> 20         


        
14条回答
  •  無奈伤痛
    2020-11-27 04:57

    I just learned how to properly use the G format specifier. See the MSDN Documentation. There is a note a little way down that states that trailing zeros will be preserved for decimal types when no precision is specified. Why they would do this I do not know, but specifying the maximum number of digits for our precision should fix that problem. So for formatting decimals, G29 is the best bet.

    decimal test = 20.5000m;
    test.ToString("G"); // outputs 20.5000 like the documentation says it should
    test.ToString("G29"); // outputs 20.5 which is exactly what we want
    

提交回复
热议问题