【问题标题】:Round values depend rounding value舍入值取决于舍入值
【发布时间】:2019-07-19 06:50:03
【问题描述】:

如果使用 round() ,如果数字高于 0.5 则四舍五入,如果数字小于 0.5 则向下舍入,我有一个条件,如果你舍入高于 0.3 将向上舍入,小于 0.3 将向下舍入。

<?php 
//normal round
echo round(3.4);         // 3
echo round(3.5);         // 4
echo round(3.6);         // 4

//round i want
echo round(3.34);         // 4
echo round(3.29);         // 3
echo round(3.3);          // 3
?>

【问题讨论】:

  • 您尝试了哪些方法,结果如何?请阅读help section中的asking
  • 添加代码 sn-ps,记录您尝试过的内容以及遇到的问题。 SO 不是代码编写服务

标签: php rounding


【解决方案1】:

您可以定义自己的舍入函数,通过从自身中减去已取底数来获得数字的分数,然后将其与您的限制进行比较。

function my_round($value, $round_up_from = 0.3) {
    $fraction = $value - floor($value);  // Get the fraction
    if ($fraction >= $round_up_from) {   // If the fraction is equal to or above threshold, ceil it
        return ceil($value);
    }
    return floor($value);                // Otherwise, floor it
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-11
    • 2019-01-26
    相关资源
    最近更新 更多