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

后端 未结 11 1875
长发绾君心
长发绾君心 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:07

    How about:

    string FormatDecimal(decimal d)
    {
        const char point = System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator[0];
        string s = d.ToString();
        // if there's no decimal point, there's nothing to trim
        if (!s.Contains(point) == -1)
            return s;
        // trim any trailing 0s, followed by the decimal point if necessary
        return s.TrimEnd('0').TrimEnd(point);
    }
    
    0 讨论(0)
  • 2021-01-31 08:12

    You can specify the format string like this:

    String.Format("{0:0.000}", x);
    
    0 讨论(0)
  • 2021-01-31 08:14

    Quite a few answers already. I often refer to this cheat sheet: http://blog.stevex.net/string-formatting-in-csharp/

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

    Somewhat hackish, but this should work:

    decimal a = 100.00M;
    string strNumber = string.Format("{0}", a);
    Console.WriteLine(strNumber.Contains('.') ? strNumber.TrimEnd('0').TrimEnd('.') : strNumber);
    
    0 讨论(0)
  • 2021-01-31 08:16
    string s = d.ToString("0.#############################");
    
    0 讨论(0)
  • 2021-01-31 08:17

    Unlike what everybody suggest to use a G format specifier I would suggest the following to preserve both thousand separator and decimal point while removing extra trailing zeros:

    {0:#,#.##}
    

    The result of this format is much better than G in most cases:

    String.Format("{0:#,#.##}",25/2.4);
    10.42
    
    String.Format("{0:#,#.##}",1000000);
    1,000,000
    
    String.Format("{0:#,#.##}",1000000.3600000);
    1,000,000.36
    

    And the G specifier can't really handle all the possible combinations:

    String.Format("{0:G29}",25/2.4);
    10.416666666666668
    
    String.Format("{0:G2}",25/2.4);
    10
    
    String.Format("{0:G29}",1000000.3600000);
    1000000.36
    
    String.Format("{0:G2}",1000000.3600000);
    1E+06
    
    0 讨论(0)
提交回复
热议问题