Best way to display decimal without trailing zeroes

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

    Another solution, based on dyslexicanaboko's answer, but independent of the current culture:

    public static string ToTrimmedString(this decimal num)
    {
        string str = num.ToString();
        string decimalSeparator = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
        if (str.Contains(decimalSeparator))
        {
            str = str.TrimEnd('0');
            if(str.EndsWith(decimalSeparator))
            {
                str = str.RemoveFromEnd(1);
            }
        }
        return str;
    }
    
    public static string RemoveFromEnd(this string str, int characterCount)
    {
        return str.Remove(str.Length - characterCount, characterCount);
    }
    

提交回复
热议问题