1

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!

1
  • 3
    It's a floating point precision issue. It's well documented on the Internet and this website.
    – John Conde
    Commented Aug 7, 2013 at 14:58

3 Answers 3

2

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.

0

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

0

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.