Javascript:累计到5的下一个倍数 [英] Javascript: Round up to the next multiple of 5
问题描述
我需要一个实用函数,它接受一个整数值(长度从2到5位),向上舍入到下一个 5的倍数,而不是最近的 5的倍数。这是我得到的:
I need a utility function that takes in an integer value (ranging from 2 to 5 digits in length) that rounds up to the next multiple of 5 instead of the nearest multiple of 5. Here is what I got:
function round5(x)
{
return (x % 5) >= 2.5 ? parseInt(x / 5) * 5 + 5 : parseInt(x / 5) * 5;
}
当我运行 round5(32)
,它给了我 30
,我想要35。
当我运行 round5(37)
,它给我 35
,我想要40。
When I run round5(32)
, it gives me 30
, where I want 35.
When I run round5(37)
, it gives me 35
, where I want 40.
当我运行 round5(132)
,它给我 130
,我想要135.
当我运行 round5(137)
,它给我 135
,我想要140.
When I run round5(132)
, it gives me 130
, where I want 135.
When I run round5(137)
, it gives me 135
, where I want 140.
等...
我该怎么做?
推荐答案
这将完成工作:
function round5(x)
{
return Math.ceil(x/5)*5;
}
这只是常见四舍五入的变体数
到最接近的 x
函数 Math.round(number / x)* x
,但是使用 .ceil
而不是 .round
根据数学规则使其始终向上舍入而不是向下/向上。
It's just a variation of the common rounding number
to nearest multiple of x
function Math.round(number/x)*x
, but using .ceil
instead of .round
makes it always round up instead of down/up according to mathematical rules.
这篇关于Javascript:累计到5的下一个倍数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!