float to double casting issue

cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

float to double casting issue

15,914 Views
BobS
Contributor III
I am trying to do a calculation where I need to convert a float number to a double to obtain added precision in a chain calculation.  I seem to have encountered a problem.  It appears that the following does not work as expected:
 
float TestFloat;
double Test;
 
TestFloat = 20.03564;
 
Test = (double)TestFloat;
 
When I look in the debugger, TestFloat shows the correct value.  But, Test shows a value of 20.035642623901367.
 
If I run the following:
 
Test = 20.03564;
 
The debugger shows the exact value as a double.
 
What is happening?
 
Thanks!
 
Labels (1)
0 Kudos
4 Replies

607 Views
BobS
Contributor III
Thank you for your help!
0 Kudos

607 Views
BobS
Contributor III
Why is it directly representable if I assign it directly, but not if I convert it using the cast? 
 
What is the point of using a double if it can not at least represent the equivalent precision of a float?
 
Thanks!
0 Kudos

607 Views
CompilerGuru
NXP Employee
NXP Employee
20.03564 is not exactly representable as double or a float. That they are printed in the debugger this way, just means that the stored value is a close approximation of it, but it is impossible that the stored value is exactly 20.0356400000000000000000000000000000000000000000000000000000000000000000000000000000.

When you print the float or the double, and you get the same text representation, this does not mean that the float and the double are identical.
No, the double representation is much more close to the value you specify, but as all the additional digits happen to be 0, they are not printed.
For the float, there is just no reason to print more digits, as those are not significant, given the float resolution.
Maybe you should not use just a short 7 digits number like 20.03564 to see the difference double makes. Use something with more digits, like 20.0356412345678901234567890123456789012345678901234567890
Here you will loose something in any case.
Also note that the value printed by the debugger is also just an appriximation of the actual stored value.
0 Kudos

607 Views
CompilerGuru
NXP Employee
NXP Employee
The point is that 20.03564 is not exactly represantible as float. Therefore when you first assign it to a float then this float to a double, the result cannot be more precise than the float representation.
When you directly assign the 20.03564 value to the double, you do get diretly double precision.
So to me, the observed behaviour is just what I would expect.

Daniel
0 Kudos