Is there a way to get a string showing the exact value of a double
, with all the decimal places needed to represent its precise value in base 10?
For example (via Jon Skeet and Tony the Pony), when you type
double d = 0.3;
the actual value of d
is exactly
0.299999999999999988897769753748434595763683319091796875
Every binary floating-point value (ignoring things like infinity and NaN) will resolve to a terminating decimal value. So with enough digits of precision in the output (55 in this case), you can always take whatever is in a double
and show its exact value in decimal. And being able to show people the exact value would be really useful when there's a need to explain the oddities of floating-point arithmetic. But is there a way to do this in C#?
I've tried all of the standard numeric format strings, both with and without precision specified, and nothing gives the exact value. A few highlights:
d.ToString("n55")
outputs0.3
followed by 54 zeroes -- it does its usual "round to what you probably want to see" and then tacks more zeroes on the end. Same thing if I use a custom format string of0.00000...
d.ToString("r")
gives you a value with enough precision that if you parse it you'll get the same bit pattern you started with -- but in this case it just outputs0.3
. (This would be more useful if I was dealing with the result of a calculation, rather than a constant.)d.ToString("e55")
outputs2.9999999999999999000000000000000000000000000000000000000e-001
-- some of the precision, but not all of it like I'm looking for.
Is there some format string I missed, or some other library function, or NuGet package or other library, that is able to convert a double
to a string with full precision?