简体   繁体   English

函数圆形 php 无法正常工作

[英]Function round php not work correctly

php function round not working correctly. php 函数round不能正常工作。 I have number 0.9950 .我有号码0.9950 I put code:我把代码:

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

And I get 1.0?我得到1.0? Why??为什么?? Why I can't get 0.99 ?为什么我不能得到0.99

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_UP
  • PHP_ROUND_HALF_DOWN PHP_ROUND_HALF_DOWN
  • PHP_ROUND_HALF_EVEN PHP_ROUND_HALF_EVEN
  • PHP_ROUND_HALF_ODD 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 :这个常量很容易理解,所以只需使用修改后的常量 :) 在您的示例中,要获得 0.99,您需要使用:

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

DEMO 演示

When you round 0.9950 to two decimal places, you get 1.00 because this is how rounding works.当你0.9950到小数点后两位,你得到1.00 ,因为这是如何四舍五入的作品。 If you want an operation which would result in 0.99 then perhaps you are looking for floating point truncation.如果您想要一个会导致0.99的操作,那么您可能正在寻找浮点截断。 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:将浮点数截断为两位小数的一种选择是乘以 100,转换为整数,然后再次除以 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.这个技巧是有效的,因为在第一步之后0.9950变为99.50 ,当转换为整数时变为99 ,丢弃原始数字中第二个小数位后的所有内容。 Then, we divide again by 100 to restore the original number, minus what we want truncated.然后,我们再次除以100以恢复原始数字,减去我们想要截断的数字。

Demo演示

Just tested in PHP Sandbox ... PHP seems funny sometimes.刚刚在PHP Sandbox 中测试... PHP 有时看起来很有趣。

<?php
    $n = 16.90;
    echo (100*$n)%100, "\n"; // 89
    echo (int)(100*$n)%100, "\n"; // 89
    echo 100*($n - (int)($n)), "\n"; // 90
    echo (int)(100*($n - (int)($n))), "\n"; // 89
    echo round(100*($n - (int)($n))), "\n"; // 90

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM