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

后端 未结 11 1885
长发绾君心
长发绾君心 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);
    }
    

提交回复
热议问题