简体   繁体   English

如何使用PHP向下舍入到下一个x20号码?

[英]how to round up to the next x20 number with php?

I know ceil, which will round 15.1 to 16 and 31.2 to 32. But how to round up to the next x20 number? 我知道ceil,它将在15.1到16和31.2到32之间。但是如何围绕下一个x20数字呢? like 15.1 to 20 and 31,2 to 40? 像15.1到20和31,2到40?

Is needed to make sensefull labels for the y-axis of a chart. 需要为图表的y轴制作有意义的标签。

Try this (works in JavaScript): 试试这个(适用于JavaScript):

$result = 20 * ceil($input / 20);

Here, we're rounding to 20 . 在这里,我们四舍五入到20 To round to other numbers, simply replace 20 with whatever base you want. 要舍入到其他数字,只需将20替换为您想要的任何基数。 The documentation for ceil() can be found here . ceil()的文档可以在这里找到。

A function that does the same: 执行相同的功能:

function roundTo($value, $base)
{
    return $base * ceil($value / $base);
}

As a small aside, if you want to round to the nearest base, instead of rounding up , use round() instead of ceil() . 作为一小部分,如果你想要舍入到最近的基数,而不是向上舍入,使用round()而不是ceil()

除以20并使用ceil,然后乘以20

或者您可以使用模数:

echo round($a + 20 - ($a % 20));

If you want "mid-range" values to round more, you can use the following . 如果您希望“中档”值更圆,可以使用以下内容

function roundTo($n,$i = 1){
  $r = $n % $i;
  $d = round(($n - $r * $i) / $i);
  return $r * $i + $d * $i;
}

for ($a = 0; $a < 100; $a++){
  printf("%d = %d\r\n", $a, ceil2($a, 20));
}

The above produces: 以上产生:

Number:    Rounded To:
0-10       0
11-30      20
31-50      40
etc.

This more closely simulates how 1.3=1 but 1.5=2 . 这更接近地模拟1.3=11.5=2

you can use this 你可以用它

ceil(x/2)*2 小区(X / 2)* 2

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

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