-1
# PHP Version 5.2.9  

$a = 0.6/0.1;  
$b = $a % 5;  
print "\$a=$a; \$b=$b\n";  
# result:  
# $a=6; $b=0   # One should expect $b = 1  

$a = 0.6/0.1;  
$a = round($a);  
$b = $a % 5;  
print "\$a=$a; \$b=$b\n";  
# result:  
# $a=6; $b=1  # result as expected  

Why is the result $b=0 in the first case.
And why does the round()-function seems to solve the problem?

Rinco
  • 27
  • 2

1 Answers1

3

Print both numbers with a bunch of decimal places and you'll see the problem, which is due to floating point imprecision:

The first $a:

5.999999999999999111821580299874767661 

The second, after round():

6.000000000000000000000000000000000000

Casting the first to int (like the mod operator does when it computes its value) results in 5, while the second results in 6.

nickb
  • 59,313
  • 13
  • 108
  • 143