Best way to display decimal without trailing zeroes

前端 未结 14 1433
终归单人心
终归单人心 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 05:11

    You can use the G0 format string if you are happy to accept scientific notation as per the documentation:

    Fixed-point notation is used if the exponent that would result from expressing the number in scientific notation is greater than -5 and less than the precision specifier; otherwise, scientific notation is used.

    You can use this format string as a parameter to the .ToString() method, or by specifying it as a within an interpolated string. Both are shown below.

    decimal input = 20.12500m;
    Console.WriteLine(input.ToString("G0")); // outputs 20.125
    Console.WriteLine($"{input:G0}"); // outputs 20.125
    
    decimal fourDecimalPlaces = 0.0001m;
    Console.WriteLine(fourDecimalPlaces.ToString("G0")); // outputs 0.0001
    Console.WriteLine($"{fourDecimalPlaces:G0}"); // outputs 0.0001
    
    decimal fiveDecimalPlaces = 0.00001m;
    Console.WriteLine(fiveDecimalPlaces.ToString("G0")); // outputs 1E-05
    Console.WriteLine($"{fiveDecimalPlaces:G0}"); // outputs 1E-05
    

提交回复
热议问题