Problem using string.Format to show a double

B

Boz

Hi,

I am trying to use string.Format() to output the value of a double.

double da = 100000000000.99994;
double db = 100000000000.9994;
double dc = 100000000000.994;
double dd = 1000000000.99994;

Debug.WriteLine(string.Format("a={0:F10}", da));
Debug.WriteLine(string.Format("b={0:F10}", db));
Debug.WriteLine(string.Format("c={0:F10}", dc));
Debug.WriteLine(string.Format("d={0:F10}", dd));

give the result:
a=100000000001.0000000000
b=100000000000.9990000000
c=100000000000.9940000000
d=1000000000.9999400000

The problem is that a is being rounded to 100000000001 in formatting.

Stepping through the code, da is correctly reported by the debugger as
100000000000.99994

Is this a limitation of string.Format() ? Is there an alterative way
to output a double without rounding?

Boz
 
G

Guest

if you are able to use (or convert) to a decimal type, it will work

this code:

decimal d = 100000000000.99994M;
System.Diagnostics.Trace.WriteLine(d.ToString());

output this
100000000000.99994

-James
 
S

Stefan Simek

Well, I guess it shouldn't do it, but nonetheless it does. If you need an
exact representation of the number, use the "R" (round-trip) format. It
guarantees that parsing the string output yields exactly the same result as
the original number.

Maybe the rounding occurs because the double is guaranteed to have only 15
significant digits. In your example, event the 16th one is a 9, so the
rounding comes into place.

Jon's DecimalConverter shows exact representations of the numbers as
follows:

100000000000.99993896484375
100000000000.9994049072265625
100000000000.9940032958984375
1000000000.99994003772735595703125

As you see, the first one is already malformed at the end. The only
difference is that the debugger probably tries to recover one more
significant digit than the double.ToString() method.

HTH,
Stefan
 
J

Jon Skeet [C# MVP]

Stefan Simek said:
Well, I guess it shouldn't do it, but nonetheless it does. If you need an
exact representation of the number, use the "R" (round-trip) format.

Just a small note of caution - round-trip *doesn't* give the exact
decimal representation.
It guarantees that parsing the string output yields exactly the same
result as the original number.

That it does.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top