Eugene Yarmash
Eugene Yarmash

Reputation: 149736

Perl modulo operator question

Why does the first example print a wrong result ?

perl -le 'print $x = 100*1.15 % 5'
4
perl -le 'print $x = 1000*1.15 % 5'
0

Upvotes: 6

Views: 1475

Answers (2)

Tassos Bassoukos
Tassos Bassoukos

Reputation: 16142

Rounding. Keep in mind that computers can't represent actual decimal places perfectly - they approximate. On my computer, perl -le 'print $x = (100*1.15)-115' gives the result -1.4210854715202e-14, which means that 100*1.15 is almost, but not quite, 115.

Upvotes: 5

NullUserException
NullUserException

Reputation: 85458

It's because of floating point arithmetic.

print $x = int(100*1.15);

Gives you 114.

Upvotes: 9

Related Questions