Before I get flamed, I want to say I do understand floating point numbers and things of the sort, but that doesn't seem to be my issue.
To simplify things, I'm trying to determine if a number has more than 2 decimal places. I'm doing this by multiplying the number by 100 (stored under variable "test1
") and then truncating it with int() ($test2)
and comparing it with an if
.
$test1 = $number * 100;
$test2 = int($test1);
unless ($test1 == $test2) {
die ("test1:$test1, test2:$test2");
}
The initial $number
comes from a whole series of other functions and should realistically be only two decimals, hence I'm trying to catch those that aren't (as a few entries seem to have very many decimals).
However, I just got:
test1:15, test2:14
from my die()
.
Can someone explain how that would happen? How can int(15)
be 14
?
From perldoc:
So, the machine representation of "15" is probably something like 14.9999999999999999 and, therefore,
int
truncates it to 14.Note that perldoc suggests using the POSIX functions
floor
orceil
instead.