Best way to display decimal without trailing zeroes

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

    I ended up with the following code:

        public static string DropTrailingZeros(string test)
        {
            if (test.Contains(CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator))
            {
                test = test.TrimEnd('0');
            }
    
            if (test.EndsWith(CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator))
            {
                test = test.Substring(0,
                    test.Length - CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator.Length);
            }
    
            return test;
        }
    

提交回复
热议问题