I have a field radius in my database of the type float and of value 0.0.
Through a PHP sript I change it’s value to the content of d2, with this statement, to 32.422:
$res=mysql_query("UPDATE `astros` SET `radius` = `radius` + ".$d2." WHERE `index` = '".$index."'");
If later I use another PHP script to reduce the value of the radius in the same amount:
$res=mysql_query("UPDATE `astros` SET `radius` = `radius` - ".$d2." WHERE `index` = '".$index."'");
the final value isn’t 0, like it should be, but 1.4988E-9… almost zero.
Can anyone tell me what am I doing wrong?
Thanks,
Direz
There is nothing wrong, you are just seing the limitation of the floating point numbers.
What you think is the exact value 32.422 isn’t so. When converted from the textual representation in the query into a floating point number used by the database, it becomes the closest number that is possible to represent using that data type. It could be something like 32.421999995662, very close to 32.422 but not exactly.
Each floating point value may contain such a deviation from the value that you intended, and when you do calculations with them the deviations add up, and after a while you see the difference.
Normally the small differences isn’t visible, as the numbers are rounded to a reasonable number of digits when you display them. If you for example subtracted 31.422 in the second query, you would end up with something that is very close to 1, for example 1.00000000014988, which would be rounded to 1.000000000 when you display it. As you are getting a value close to zero, there is no value substantially larger than the deviation that it could round to, so you see only the deviation.