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;
}
这只是普通四舍五入number
到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屋!