problem with double conversion ?

Started by loo, May 21, 2015, 11:21:29 PM

Previous topic - Next topic

loo

Hi,

I compiled a json parser (parson) which has also a test suite included. I wondered why two test cases failed and reduced it to the following:


printf("%f\n", (double)-9876.543210);
printf("%f\n", (double)0.123456789e-12);
printf("%f\n", (double)1.234567890E+34);
printf("%f\n", (double)23456789012E66);


The output with Pelles C 8.00.60 under Win 8.1 is:
-9876.543210
0.000000
12345678900000001303851000000000000.000000
23456789012000001093800000000000000000000000000000000000000000000000000000000.000000

I was expecting something like:
-9876.543210
0.000000000000123456789
12345678900000000000000000000000000.000000
23456789012000000000000000000000000000000000000000000000000000000000000000000.000000

Any ideas ?

Regards
Otto

MichaelW

The default precision is 6 decimal places, but you can specify a greater precision (for a double the realistic limit is ~15 significant digits):

printf("%.16f\n", (double)0.123456789e-12);


Result: 0.0000000000001235



loo

Right. My mistake. Meanwhile I got this too   ;)
But what I'm really interested in is the 3rd and the 4th line. Where are the ghost digits in the middle of the number coming from ?  :o

frankie

Quote from: loo on May 22, 2015, 09:19:15 AM
But what I'm really interested in is the 3rd and the 4th line. Where are the ghost digits in the middle of the number coming from ?  :o
Rounding and float irriducible fractions (numbers that expressed in base 2 give irrational or periodic fractional number).
"It is better to be hated for what you are than to be loved for what you are not." - Andre Gide