0

For example if double a = 34.837864 and float b = (float)a why does b have different decimals if b is in the range of float?

Or in this other example:

float a = 3.38776326737464747726337264343434334434343;
double b = 3.38776326737464747726337264343434334434343; 

printf("%.16f\n%.16lf",a,b);

The output is a=3.3877632617950439 and b=3.3877632673746474. We can see that there are some decimals that are different.

Why does the output has different decimals if both of them are printing the same number and this number is in the range of float and double?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Tenko
  • 123
  • 5
  • 3
    Does this answer your question? [Why are floating point numbers inaccurate?](https://stackoverflow.com/questions/21895756/why-are-floating-point-numbers-inaccurate) – Passerby Nov 29 '21 at 22:32
  • 8
    `double` doesn't merely have a greater *range* than `float`, it also has greater *precision* (more significant figures). – Fred Larson Nov 29 '21 at 22:32
  • 2
    Internally, both `float` and `double` use *binary* floating point. Type `float` has 24 bits worth of precision, and `double` has 53 bits. Your number 3.38776326737... is (in binary) `0b11.0110001101000100011101` as a `float`, and `0b11.011000110100010001110100000101111111011011010110110` as a `double`. You can see that, in binary, the `float` representation is a subset of `double`. But when you convert back to decimal, you get (approximately) 3.3877632618 and 3.38776326737464739, which don't quite match so well — although they do have the prefix 3.38776326 in common. – Steve Summit Nov 29 '21 at 23:11
  • [Is there a functional difference between "2.00" and "2.00f"?](https://stackoverflow.com/q/7697148/995714) – phuclv Nov 30 '21 at 02:02

0 Answers0