0

Easier to see via examples.

All of them with the following php version:

$ php --version
PHP 7.4.4 (cli) (built: Mar 18 2020 04:33:54) ( NTS )
...

Exhibit 1:

$ echo '<?php for ($i = 0; $i <= 10; ++$i ) {  print( (int)(100 * ($i + 0.7)) . "\n"); } ?>' | php
70
170
270
370
470
570
670
770
869  <<< uh?
969  <<< uh?
1070

Exhibit 2 replacing the type casting by float:

$ echo '<?php for ($i = 0; $i <= 10; ++$i ) {  print( (float)(100 * ($i + 0.7)) . "\n"); } ?>' | php
70
170
270
370
470
570
670
770
870
970
1070

The question is:

Why does the Exhibit 1 results happen?

ateam
  • 137
  • 1
  • 11
  • Floating point math is approximate. Sometimes the result will be something like `869.9999999999`. `int()` rounds down, but printing the float rounds to the closest. – Barmar Mar 18 '20 at 21:56
  • Use `round()` instead of `int()`. – Barmar Mar 18 '20 at 21:56
  • If you feel like reading [more on the subject](https://stackoverflow.com/questions/588004/is-floating-point-math-broken). – El_Vanja Mar 18 '20 at 22:03

0 Answers0