Reputation: 378
Have a look at this my friend and tell me I'm not crazy...
echo (int) (9.45 * 100); // gives 944
echo (int) 945; // gives 945
I don't understand why the first instruction would return 944!???? Is this a known php issue? help is appreciated as always!
Upvotes: 1
Views: 1823
Reputation: 6902
If you convert the float to string before converting to int, the int will result as expected:
echo (int)(9.45 * 100); // 944
echo (int)(string)(9.45 * 100); // 945
Upvotes: 0
Reputation: 3694
Floating point numbers have limited precision. Although it depends on the system, PHP typically uses the IEEE 754 double precision format, which will give a maximum relative error due to rounding in the order of 1.11e-16.
Additionally, rational numbers that are exactly representable as floating point numbers in base 10, like 0.1 or 0.7, do not have an exact representation as floating point numbers in base 2, which is used internally, no matter the size of the mantissa. Hence, they cannot be converted into their internal binary counterparts without a small loss of precision.
This can lead to confusing results: for example, floor((0.1+0.7)*10)
will usually return 7 instead of the expected 8, since the internal representation will be something like 7.9999999999999991118....
So never trust floating number results to the last digit, and do not compare floating point numbers directly for equality.
for more information you can check at http://php.net/manual/en/language.types.float.php
Upvotes: 0
Reputation: 4709
According to PHP documentation (http://php.net/manual/en/language.types.integer.php)
When converting from float to integer, the number will be rounded towards zero.
That's why you are getting 944.
Upvotes: 2