3
echo 65.7 * 100 % 10 // 0

echo 65.6 * 100 % 10 // 9 <---

echo 6560 % 10       // 0

echo 65.5 * 100 % 10 // 0

Can someone please explain why?

EDIT:

for human or non-programmers, the result 9 is apprently wrong.

how can I prevent this "error" when programming?

user1643156
  • 4,407
  • 10
  • 36
  • 59

4 Answers4

4

Because 65.6 in floating point is actually an approximation of 65.6. It is actually marginally less than 65.6, i.e. 65.5999 or similar.

Assuming my wild guess at the actual value is correct, you have 6559.9, which is stripped to 6599 by the modulus operator, then divided by 10 for remainder 9.

Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139
3

Because 65.6 * 100 is 6559.9999999999.

That's floating points for you.

Community
  • 1
  • 1
Thilo
  • 257,207
  • 101
  • 511
  • 656
2

As already stated, this has to do with floating point arithmetic. I recommend reading What Every Computer Scientist Should Know About Floating-Point Arithmetic.

alexn
  • 57,867
  • 14
  • 111
  • 145
1

Because:

<?php

echo (65.7 * 100 == 6570) ? "Equal" : "Not equal";  // Equal
echo (65.6 * 100 == 6560) ? "Equal" : "Not equal";  // NOT EQUAL !!
echo (65.5 * 100 == 6550) ? "Equal" : "Not equal";  // Equal

?>

65.6 * 100 is NOT 6560. The big red warning box here explains why.

Aziz
  • 20,065
  • 8
  • 63
  • 69