0

I'm looking for an explanation of a very weird PHP behaviour. By accident, we found a case where PHP rounds down an integer.

So in the following examples: floor(2.05 * 100) == 204 is true as well as (int)(2.05 * 100) === 204.

Both cases seem to be incorrect as floor() or (int) should result in a number 205, not 204.

When multiplying the number by 1000 and divide by 10 the result is correct while using (int): (int)((2.05 * 1000) / 10) === 205, but still incorrect when using floor().

Can you please advise why that happened?

My PHP version is 7.3.8, but possibly it's the same on the older versions as well.

Many thanks!

MrTomAsh
  • 174
  • 1
  • 8
  • 1
    I suspect it has something to do with the inability of most floating point numbers to represent integers exactly. ceil() probably would have worked in your first example. – mlewis54 Nov 20 '19 at 16:54
  • Both `floor(2.05 * 100) == 204` and `(int)(2.05 * 100) === 204` are effectively doing the same thing. The `==` operator will cause the float returned by floor to be cast to int because of PHP type juggling. This is a common issue with floating point numbers that is well documented. Basically, there is an internal rounding error due to the fixed nature of binary machines. (Ex: 205 is really 204.9999999999 internally) The closest you will get is something like `round(2.05 * 100, 0) == 205` Read about how floating point is represented in binary. – Alex Barker Nov 20 '19 at 17:34

0 Answers0