1

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); ?>
Community
  • 1
  • 1
manojadams
  • 2,314
  • 3
  • 26
  • 30

2 Answers2

6

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.

UltraInstinct
  • 43,308
  • 12
  • 81
  • 104
  • Any idea how to circumvent this issue? – arik Jul 10 '12 at 11:10
  • to circumvent it, use bcmath - http://uk.php.net/manual/en/book.bc.php - gmp - http://uk.php.net/manual/en/book.gmp.php - or similar, or use the appropriate rounding rather than simply casting to int – Mark Baker Jul 10 '12 at 11:12
  • Looks like this works: `(int)(string)((0.1+0.7)*10);` But it's not an universal solution. – Mārtiņš Briedis Jul 10 '12 at 11:12
  • Ok, thanks. I also thought about multiplying with 10, rounding, dividing by ten, and then proceeding to do whatever it was, but the error might persist regardlessly. – arik Jul 10 '12 at 11:15
  • @MartinsBriedis: Try doing the same thing with `printf(..)` with a higher decimal precision. Arik-so: The answer is there is always a better way of doing it depending on what you want to do. – UltraInstinct Jul 10 '12 at 11:16
  • In *this particular case*, `round((0.1+0.7)*10);` – JJJ Jul 10 '12 at 19:16
1

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.

Rudolph Gottesheim
  • 1,671
  • 1
  • 17
  • 30