Function round php not work correctly

喜你入骨 提交于 2019-12-24 08:56:48

问题


php function round not working correctly. I have number 0.9950. I put code:

$num = round("0.9950", 2);

And I get 1.0? Why?? Why I can't get 0.99?


回答1:


You can add a third parameter to the function to make it do what you need. You have to choose from one of the following :

  • PHP_ROUND_HALF_UP
  • PHP_ROUND_HALF_DOWN
  • PHP_ROUND_HALF_EVEN
  • PHP_ROUND_HALF_ODD

This constants are easy enough to understand, so just use the adapted one :) In your example, to get 0.99, you'll need to use :

<?php echo round("0.9950", 2, PHP_ROUND_HALF_DOWN); ?>

DEMO




回答2:


When you round 0.9950 to two decimal places, you get 1.00 because this is how rounding works. If you want an operation which would result in 0.99 then perhaps you are looking for floating point truncation. One option to truncate a floating point number to two decimal places is to multiply by 100, cast to integer, then divide again by 100:

$num = "0.9950";
$output = (int)(100*$num) / 100;
echo $output;

0.99

This trick works because after the first step 0.9950 becomes 99.50, which, when cast to integer becomes just 99, discarding everything after the second decimal place in the original number. Then, we divide again by 100 to restore the original number, minus what we want truncated.

Demo



来源:https://stackoverflow.com/questions/48368421/function-round-php-not-work-correctly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!