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

后端 未结 11 1909
长发绾君心
长发绾君心 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:18

    They're not necessarily meaningless - they indicate the precision during calculation. Decimals maintain their precision level, rather than being normalized.

    I have some code in this answer which will return a normalized value - you could use that, and then format the result. For example:

    using System;
    using System.Numerics;
    
    class Test
    {
        static void Display(decimal d)
        {
            d = d.Normalize(); // Using extension method from other post
            Console.WriteLine(d);
        }
    
        static void Main(string[] args)
        {
            Display(123.4567890000m); // Prints 123.456789
            Display(123.100m);        // Prints 123.1
            Display(123.000m);        // Prints 123
            Display(123.4567891234m); // Prints 123.4567891234
        }
    }
    

    I suspect that most of the format string approaches will fail. I would guess that a format string of "0." and then 28 # characters would work, but it would be very ugly...

提交回复
热议问题