skndstry
skndstry

Reputation: 671

Weird modulo result

I observed the following and would be thankful for an explanation.

$amount = 4.56;
echo ($amount * 100) % 5;

outputs : 0

However,

$amount = 456;  
echo $amount % 5;

outputs : 1

I tried this code on two separate PHP installations, with the same result. Thanks for your help!

Upvotes: 1

Views: 168

Answers (2)

Artefact2
Artefact2

Reputation: 7644

Use fmod to avoid this problem.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1502016

I strongly suspect this is because 4.56 can't be exactly represented as a binary floating point number, so a value very close to it is used instead. When multiplied by 100, that comes to 455.999(something), and then the modulo operator truncates down to 455 before performing the operation.

I don't know the exact details of PHP floating point numbers, but the closest IEEE-754 double to 4.56 is 4.55999999999999960920149533194489777088165283203125.

So here's something to try:

$amount = 455.999999999;
echo $amount % 5;

I strongly suspect that will print 0 too. From some PHP arithmetic documentation:

Operands of modulus are converted to integers (by stripping the decimal part) before processing.

Upvotes: 6

Related Questions