0

I have a situation where I cast a double variable to integer. and its giving me wrong result. Why is this happening?

>>> $amount = (double) 1052.10
=> 1052.1
>>> $amount = $amount * 100;
=> 105210.0
>>> (int) $amount;
=> 105209 // weird 

I am able to fix it by rounding the variable first ( ie: (int) round($amount)),

But still, I wonder why is this happening?

using PHP 7.2.9

Shobi
  • 10,374
  • 6
  • 46
  • 82
  • 1
    This could be due to floating point precision. https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html – Ananth Oct 13 '18 at 18:32

1 Answers1

0

The 'warning' section here states:

Additionally, rational numbers that are exactly representable as floating point numbers in base 10, like 0.1 or 0.7, do not have an exact representation as floating point numbers in base 2, which is used internally, no matter the size of the mantissa. Hence, they cannot be converted into their internal binary counterparts without a small loss of precision.

Unknown
  • 769
  • 2
  • 7
  • 17