Good day everyone.

PHP version 5.6.37

There is such a code

$n = ceil(99 * ((10 / 100) * (10 / 100))); 

in the course of calculations we get just 1

but ceil rounds it to 2

I understand that the type obtained during the calculations is double and it is possible that this bug is related to this, but for example such a code

 $n = ceil((double)1.00); 

or such

 $n = ceil(100 * 0.01); 

works as expected and returns 1.

If any ideas why this happens? And how can this be fixed?

  • one
    PHP 5.6.36 - echo ceil(99 * ((10 / 100) * (10 / 100))) 10/100 echo ceil(99 * ((10 / 100) * (10 / 100))) 10/100 echo ceil(99 * ((10 / 100) * (10 / 100))) displays exactly 1 - andreymal
  • Updated to PHP 5.6.37 - still displays exactly 1, your problem could not be reproduced - andreymal
  • It would be more interesting to look at the non-rounded result and the results of expressions in brackets. What does your platform do before rounding? - Yegor Banin
  • I apologize for the inaccuracy in the question for me at 99, too, everything is fine and displays as needed, but at 100 we already get 1 and displays 2 ((10/100) * (10/100)) we have 1 out but round ceil it to 2 why? and how to fix it? - Igor Branitsky

1 answer 1

Try to execute the code

$n = 100 * ((10 / 100) * (10 / 100)); printf("%.18f\n",$n);

And see the result.

You have a floating point number, and such numbers cannot accurately represent all rational numbers. Therefore, the result of an integer transform always has uncertainty about one unit.

  • Thanks, I thought so, I just didn’t know how to print $n to display exact calculations. Nakostylyal such a function is it normal to use such in production function ceilCustom($n){ return preg_match('/\.[0-9]+/', (string)$n) ? ceil($n) : $n; } function ceilCustom($n){ return preg_match('/\.[0-9]+/', (string)$n) ? ceil($n) : $n; } function ceilCustom($n){ return preg_match('/\.[0-9]+/', (string)$n) ? ceil($n) : $n; } - Igor Branitsky
  • You can simply leave the number of float with two characters after the comma, for example, sprintf ('% 0.2f', $ n), and after that do ceil. It depends on what your task is. - EatMyDust pm