Search code examples
c#stringdoublevalueconverter

Double to string with mandatory decimal point


This is probably dumb but it's giving me a hard time. I need to convert/format a double to string with a mandatory decimal point.

1         => 1.0
0.2423423 => 0.2423423
0.1       => 0.1
1234      => 1234.0

Basically, I want to output all decimals but also make sure the rounded values have the redundant .0 too. I am sure there is a simple way to achieve this.


Solution

  • There is not a built in method to append a mandatory .0 to the end of whole numbers with the .ToString() method, as the existing formats will truncate or round based on the number of decimal places you specify.

    My suggestion is to just roll your own implementation with an extension method

    public static String ToDecmialString(this double source)
    {
        if ((source % 1) == 0)
            return source.ToString("f1");
        else
            return source.ToString();
    
    }
    

    And the usage:

    double d1 = 1;
    double d2 = 0.2423423;
    double d3 = 0.1;
    double d4 = 1234;
    Console.WriteLine(d1.ToDecimalString());
    Console.WriteLine(d2.ToDecimalString());
    Console.WriteLine(d3.ToDecimalString());
    Console.WriteLine(d4.ToDecimalString());
    

    Results in this output:

    1.0
    0.2423423
    0.1
    1234.0