Possible Duplicate:
PHP Math Precision
The following php code outputs 7 but I expect 8. Why the difference?
<?php echo (int)((0.1+0.7)*10); ?>
Possible Duplicate:
PHP Math Precision
The following php code outputs 7 but I expect 8. Why the difference?
<?php echo (int)((0.1+0.7)*10); ?>
Because due to inaccurate floating point representations, 0.1+0.7 is not exactly equal to 0.8. It might be some very tiny bit less than that. And when you use int(..)
, it truncates it to 7.
Others already pointed out the problem. If you're working with a fixed number of decimal places (for example, when working with money), you're better off calculating and storing cents and convertig them back to Dollars/Euros/Whatever when showing the values to the user.