2

Why would on earth PHP convert the result of (int) ((0.1+0.7)*10) to 7, not 8? I know that the result will be (float) 8 when it's cast to (int) the result will be 7? Why does that happen?

walrii
  • 3,392
  • 2
  • 24
  • 45
Alireza
  • 5,172
  • 10
  • 43
  • 109

2 Answers2

11

It is all about float. See PHP: Floating point numbers:

Warning - Floating point precision

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. Non elementary arithmetic operations may give larger errors, and, of course, error propagation must be considered when several operations are compounded.

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. If higher precision is necessary, the arbitrary precision math functions and gmp functions are available.

Additional reading:

Community
  • 1
  • 1
Hailei
  • 41,743
  • 6
  • 42
  • 69
  • Advising people never to trust floating-point results to the last digit is excessive. I understand that most people who use floating-point do not understand it, and they obtain and tolerate inaccurate results. However, floating-point arithmetic is well defined, and people who learn its rules and learn how to use it can design code that gets accurate and well specified results. I would prefer to encourage people to learn the rules rather than to treat them as unfathomable mysteries. – Eric Postpischil Jul 20 '12 at 11:11
  • @EricPostpischil The last paragraph which advises people "never trust floating number results to the last digit" is not written by me... It's from an article of the PHP official manual, as I provided the link. – Hailei Jul 21 '12 at 08:22
1

Halley's answer is great.

The additional info you need is that casting to int always truncates the decimals, no matter how close they are to the next number. So (int) 7.999999999999 will be 7.

It is often customary to round as you cast to get to the nearest, for example

(int) (x + 0.5)

There are many functions that will handle floating point and rounding, truncating, etc. You need to read them and choose the one that fits your needs.

walrii
  • 3,392
  • 2
  • 24
  • 45