This question has already been answered:

I am writing this code:

$sum = 161.98; $sum = $sum * 100; var_dump($sum); // float(16198) var_dump((int)$sum); // int(16197) 

Why the unit is lost when converting to int

Reported as a duplicate by Ipatiev php Jan 21 at 12:47 pm

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

    2 answers 2

    Try to use rounding up.

     var_dump((int)ceil($sum)); 

      Why the unit is lost when converting to int

      Because due to the peculiarities of floating point arithmetic, 161.98 * 100 can be equal to 16197.9999999.

      When outputting float, this is taken into account, and when converting to int, the fractional part is simply discarded.

      What to do with it - round up before conversion. Only not in the way IvanTokar advises, but to the nearest integer, through the round

      • And 16198.000000001 can not work? those. only down can get out? - Rochfort
      • Maybe in both directions. But if the error is larger, then dropping the fractional part will give exactly the result that you need. - German Borisov