简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM