Reputation: 27875
How come the result for
intval("19.90"*100)
is
1989
and not 1990
as one would expect (PHP 5.2.14)?
Upvotes: 3
Views: 1670
Reputation: 13868
I believe the php doc at https://www.php.net/manual/en/function.intval.php is omitting the fact that intval will not deliver "the integer value" but the integer (that is non-fractional) part of the number. It does not round.
Upvotes: 1
Reputation: 14938
You can also use bc* function for working with float :
$var = bcmul("19.90", "100");
echo intval($var);
Upvotes: 3
Reputation: 97805
That's because 19.90 is not exactly representable in base 2 and the closest approximation is slightly lower than 19.90.
Namely, this closest approximation is exactly 2^-48 × 0x13E66666666666. You can see its exact value in decimal form here, if you're interested.
This rounding error is propagated when you multiply by 100. intval
will force a cast of the float to an integer, and such casts always rounds towards 0, which is why you see 1989
. Use round
instead.
Upvotes: 13
Reputation: 5058
Why are you using intval
on a floating point number? I agree with you that the output is a little off but it has to do with the relative inprecision of floating point numbers.
Why not just use floatval("19.90"*100)
which outputs 1990
Upvotes: 1
Reputation: 14568
intval converts doubles to integers by truncating the fractional component of the number. When dealing with some values, this can give odd results. Consider the following:
print intval ((0.1 + 0.7) * 10);
This will most likely print out 7, instead of the expected value of 8.
For more information, see the section on floating point numbers in the PHP manual
Upvotes: 2