0

I've got a cheeky little PHP issue with conversion to int where the result is one less than I believe it should be.

(int) 4005 = 4005 (Correct)

(40.05 * 100) = 4005 (Correct)

(int) (40.05 * 100) = 4004 ??????

Any ideas?

Many thanks in advance for any help

Colin

Culky
  • 43
  • 4
  • That is a probably a rounding error. 50.05 cannot be represented as a float as the divisor is not a power of 2 (it's 5) – mousetail Nov 03 '21 at 15:27
  • Thanks for you reply. I tried to read the solution but I'm too stupid to understand it haha. Is there is a simple php solution that could make (int) (40.05 * 100) = 4005? – Culky Nov 03 '21 at 15:32
  • 3
    `40.05 * 100` is roughly `4004.9999999999995` ([fiddle](https://3v4l.org/c8j2t#v8.1rc3)). You can get an online IEEE 754 simulator if you're curious about the details. `(int)` truncates. If you want to round, you can use `round()`. – Álvaro González Nov 03 '21 at 15:33
  • Can this issue be reopened as no solution has been made. The linked answer is in javascript and horrendously complex. – Culky Nov 03 '21 at 15:37
  • floating point number work the same in every language, and are a bit complex topic no matter how you phrase it – mousetail Nov 03 '21 at 15:38
  • So what is the php solution? – Culky Nov 03 '21 at 15:39
  • See @ÁlvaroGonzález's comment - [demo](https://ideone.com/Nad6kO) – DarkBee Nov 03 '21 at 15:41
  • Apologies, many thanks guys that's perfect – Culky Nov 03 '21 at 15:42
  • Search "is floating point broken" and take your pick of hundered of pages of info – RiggsFolly Nov 03 '21 at 15:44
  • Read this: https://stackoverflow.com/questions/3726721/php-floating-number-precision – devMariusz Nov 03 '21 at 18:55

0 Answers0