Javascript:累计到5的下一个倍数

Ami*_*ole 96 javascript math rounding

我需要一个实用函数,它接受一个整数值(长度从2到5位),向上舍入到5的下一个倍数,而不是最近的5的倍数.这是我得到的:

function round5(x)
{
    return (x % 5) >= 2.5 ? parseInt(x / 5) * 5 + 5 : parseInt(x / 5) * 5;
}
Run Code Online (Sandbox Code Playgroud)

当我跑步时round5(32),它给了我30,我想要的地方35.
当我跑步时round5(37),它给了我35,我想要的地方40.

当我跑步时round5(132),它给了我130,我想要的地方135.
当我跑步时round5(137),它给了我135,我想要的地方140.

等等...

我该怎么做呢?

paw*_*wel 238

这将做的工作:

function round5(x)
{
    return Math.ceil(x/5)*5;
}
Run Code Online (Sandbox Code Playgroud)

它只是公共舍入numberx函数的最接近倍数的变化Math.round(number/x)*x,但是使用.ceil而不是.round使它总是向上舍入而不是根据数学规则向下/向上舍入.

  • 我喜欢这个解决方案!我用一个闭包实现了它,以便根据需要方便地更改多个内联:const roundToNearestMultipleOf = m => n => Math.round(n / m)* m`用法:roundToNearestMultipleOf(5)(32)` (3认同)
  • 好吧,它确实在这里舍入到整数,@ AmitErandole;) (2认同)

Spe*_*thy 22

const roundToNearest5 = x => Math.round(x/5)*5
Run Code Online (Sandbox Code Playgroud)

这会将数字四舍五入到最接近的 5。要始终四舍五入到最接近的 5,请使用Math.ceil。同样,要始终向下舍入,请使用Math.floor代替Math.round。然后,您可以像调用其他函数一样调用此函数。例如,

roundToNearest5(21)
Run Code Online (Sandbox Code Playgroud)

将返回:

20
Run Code Online (Sandbox Code Playgroud)


Mic*_*ker 6

像这样?

function roundup5(x) { return (x%5)?x-x%5+5:x }
Run Code Online (Sandbox Code Playgroud)


Aym*_*Kdn 6

我是在寻找类似物品时到达这里的。如果我的数字是-0,-1,-2,则应降到-0,如果它是-3,-4,-5,则应降到-5。

我想出了这个解决方案:

function round(x) { return x%5<3 ? (x%5===0 ? x : Math.floor(x/5)*5) : Math.ceil(x/5)*5 }
Run Code Online (Sandbox Code Playgroud)

和测试:

for (var x=40; x<51; x++) {
  console.log(x+"=>", x%5<3 ? (x%5===0 ? x : Math.floor(x/5)*5) : Math.ceil(x/5)*5)
}
// 40 => 40
// 41 => 40
// 42 => 40
// 43 => 45
// 44 => 45
// 45 => 45
// 46 => 45
// 47 => 45
// 48 => 50
// 49 => 50
// 50 => 50
Run Code Online (Sandbox Code Playgroud)

  • 这可以通过使用“Math.round”更简单地完成 (2认同)