Best way to display decimal without trailing zeroes

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

    I don't think it's possible out-of-the-box but a simple method like this should do it

    public static string TrimDecimal(decimal value)
    {
        string result = value.ToString(System.Globalization.CultureInfo.InvariantCulture);
        if (result.IndexOf('.') == -1)
            return result;
    
        return result.TrimEnd('0', '.');
    }
    

提交回复
热议问题