Search code examples
c#floating-pointnumber-formattingfloating-accuracy

How to print floating point numbers in full precision


If I have a value of 0.3 which can not accuratly represented by double or float how can I print it's real value as string. A program like this:

using System;
class Program 
{
    static void Main(string[] args) 
    {
        var line = Console.ReadLine();
        var d = float.Parse(line);
        Console.WriteLine("{0:R}", d);
    }
}

with 0.3 as input does print 0.3 which is odd to me since according to this it should be something like 0.300000011920928955078125.

So the question is how can I force .net to format float/double as its real value.


Solution

  • According to Standard numeric format strings

    R recommended for the BigInteger type only. For Double types, use "G17"; for Single types, use "G9".

    So, try to use G9 (because float gives you up to 9 significant digits of precision), it gives you an expected output

    Console.WriteLine("{0:G9}", d);
    

    At my end I'll see 0.300000012 value