Best way to display decimal without trailing zeroes

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

    Do you have a maximum number of decimal places you'll ever need to display? (Your examples have a max of 5).

    If so, I would think that formatting with "0.#####" would do what you want.

        static void Main(string[] args)
        {
            var dList = new decimal[] { 20, 20.00m, 20.5m, 20.5000m, 20.125m, 20.12500m, 0.000m };
    
            foreach (var d in dList)
                Console.WriteLine(d.ToString("0.#####"));
        }
    
    0 讨论(0)
  • 2020-11-27 05:22

    You can create extension method

    public static class ExtensionMethod {
      public static decimal simplify_decimal(this decimal value) => decimal.Parse($"{this:0.############}");
    }
    
    0 讨论(0)
提交回复
热议问题