PHP integer rounding problems

后端 未结 5 1190
-上瘾入骨i
-上瘾入骨i 2021-01-13 08:31

echo (int) ( (0.1+0.7) * 10 );

Why does the above output 7? I understand how PHP rounds towards 0, but isn\'t (0.1+0.7) * 10 evaluated as

5条回答
  •  一个人的身影
    2021-01-13 08:50

    The other answers explained WHY this happens. This should get you what you want:

    echo (int) round( (0.1+0.7) * 10 );
    

    Just round the float before casting it to an int.

提交回复
热议问题