Search code examples
c#.netnumber-formatting

.Net - General numeric formatting does not seem to preserve zeros


Looking at the documentation on Standard Numeric Format Strings. It says

However, if the number is a Decimal and the precision specifier is omitted, fixed-point notation is always used and trailing zeros are preserved.

To me, the definition of trailing zeros just means any zeros at the end of a number, regardless of whether they are before or after the decimal point.

So, 300 and 3.00 both have 2 trailing zeros based on my understanding of trailing zeros.

However, when I actually try it out, it seems that only trailing zeros before the decimal point are preserved.

Am I just misunderstanding the definition of trailing zeros here, or is there a case where zeros after the decimal will be preserved?

using System;

public class Program
{
    public static void Main()
    {
        Console.WriteLine(new Decimal(10.000).ToString("G"));
        Console.WriteLine(new Decimal(0.000000).ToString("G"));
        Console.WriteLine(new Decimal(30000).ToString("G"));
    }
}

See example: https://dotnetfiddle.net/O2GwOY


Solution

  • The problem is that you are not specifying the number as decimal but as double literal. Since double does not preserve trailing zeroes, the constructor does not see them. For the first two examples you are using the constructor

    public Decimal (double value)
    

    and for the last one

    public Decimal (int value)
    

    Try:

    Console.WriteLine(10.000m.ToString("G"));
    Console.WriteLine(0.000000m.ToString("G"));
    Console.WriteLine(30000m.ToString("G"));
    

    The m type suffix ("m" for money) specifies a decimal number. This works as expected.

    This works as well:

    Convert.ToDecimal("10.0000").ToString("G")
    

    or

    Decimal.Parse("10.0000").ToString("G")
    

    See: Value types table (C# Reference)