douli4337 2014-05-24 02:09
浏览 60
已采纳

php舍入值,尾随2位小数,5位的倍数

I tried this function

function roundUpToAny($n,$x=5) {
    return (round($n)%$x === 0) ? round($n) : round(($n+$x/2)/$x)*$x;
}

echo roundUpToAny(4.52); // This show 5 instead of 4.55

echo roundUpToAny(5.1); // This show 5 instead of 5.10

How can i created such function

  • 写回答

1条回答 默认 最新

  • dongran1779 2014-05-24 02:33
    关注

    I think the following function does what you want:

    function roundUpToAny($n, $x=5, $sf=2) {
      $scale = pow(10,$sf);
      return number_format(round(ceil($n*$scale / $x), $sf) * $x / $scale, $sf);
    }
    

    The first argument is the number to be converted, the second is the "rounding factor" (multiples of $x - you asked for 5 in the title of the question), the third is the number of figures after the decimal point.

    Test:

    echo roundUpToAny(1.23, 5, 2) ."
    ";
    echo roundUpToAny(4.54, 5, 2) ."
    ";
    echo roundUpToAny(5.101, 5, 3) ."
    ";
    echo roundUpToAny(1.19, 5, 3) ."
    ";
    

    Result:

    1.25
    4.55
    5.105
    1.190
    

    UPDATE

    You pointed out in a follow-up that the above code fails for inputs of 1.1 and 2.2. The reason for this is the fact that these numbers are not exactly representable in double precision (strange though this may sound). The following code compensates for this, by creating an intermediate value that is rounded to be an integer (and therefore can be represented exactly):

    function roundUpToAny($n, $x=5, $sf=2) {
      $scale = pow(10,$sf);
      $temp = round($n * $scale, $sf); // get rid of small rounding errors
      return number_format(round(ceil($temp / $x), $sf) * $x / $scale, $sf);
    }
    

    Testing:

    echo roundUpToAny(1.1, 5, 2) ."
    ";
    

    Result:

    1.10
    

    As expected.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度