How do I format a C# decimal to remove extra following 0's?

后端 未结 11 1850
长发绾君心
长发绾君心 2021-01-31 07:40

I want to format a string as a decimal, but the decimal contains some following zeros after the decimal. How do I format it such that those meaningless 0\'s disappear?

相关标签:
11条回答
  • 2021-01-31 08:18

    You can use ToString() with the General ("G") Format Specifier to achieve the desired result. Trailing zeros are truncated when using this format string with a precision specified. In order to prevent rounding in any situations, you will need to set the precision to the maximum allowed for decimals (29).

    The line of code to produce what you want is number.ToString("G29"), where number is your original decimal.

    Be aware that any numbers smaller than 0.0001 will be converted to scientific notation. More details on how this formatter works can be found at the reference link above.

    0 讨论(0)
  • 2021-01-31 08:18

    They're not necessarily meaningless - they indicate the precision during calculation. Decimals maintain their precision level, rather than being normalized.

    I have some code in this answer which will return a normalized value - you could use that, and then format the result. For example:

    using System;
    using System.Numerics;
    
    class Test
    {
        static void Display(decimal d)
        {
            d = d.Normalize(); // Using extension method from other post
            Console.WriteLine(d);
        }
    
        static void Main(string[] args)
        {
            Display(123.4567890000m); // Prints 123.456789
            Display(123.100m);        // Prints 123.1
            Display(123.000m);        // Prints 123
            Display(123.4567891234m); // Prints 123.4567891234
        }
    }
    

    I suspect that most of the format string approaches will fail. I would guess that a format string of "0." and then 28 # characters would work, but it would be very ugly...

    0 讨论(0)
  • 2021-01-31 08:20
    double a = 1100.00
    double  b =1100.1
    double  c = 1100.100
    double  d =1100.1000
    
    Remove last zero after point
    
    
    string stra = a.toString("0.00").TrimEnd('0').TrimEnd('.');
    string strb = b.toString("0.00").TrimEnd('0').TrimEnd('.');
    string strc = c.toString("0.00").TrimEnd('0').TrimEnd('.');
    string strd = d.toString("0.00").TrimEnd('0').TrimEnd('.');
    
    Output
    
    1100
    1100.1
    1100.1
    1100.1
    
    0 讨论(0)
  • 2021-01-31 08:24
    String.Format("{0:0.##}", 123.0); // "123"
    
    0 讨论(0)
  • 2021-01-31 08:25

    I believe you want to do:

    var s = String.Format("{0:#####.###}");
    
    0 讨论(0)
提交回复
热议问题