Javascript:四舍五入到下一个5的倍数

Javascript:四舍五入到下一个5的倍数,javascript,math,rounding,Javascript,Math,Rounding,我需要一个实用函数,它接受一个整数值(长度从2到5位数不等),该整数值向上取整为下一个5的倍数,而不是最近的5的倍数。以下是我得到的: 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 当我运行round5(132)时,它会

我需要一个实用函数,它接受一个整数值(长度从2到5位数不等),该整数值向上取整为下一个5的倍数,而不是最近的5的倍数。以下是我得到的:

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

当我运行
round5(132)
时,它会给我
130
,我想要135。
当我运行
round5(137)
时,它会给我
135
,我想要的是140

等等

我该怎么做

if( x % 5 == 0 ) {
    return int( Math.floor( x / 5 ) ) * 5;
} else {
    return ( int( Math.floor( x / 5 ) ) * 5 ) + 5;
}
也许吧?

这样就可以了:

function round5(x)
{
    return Math.ceil(x/5)*5;
}
它只是普通四舍五入
number
的一种变体,它是
x
函数
Math的最接近倍数。四舍五入(number/x)*x
,但使用
.ceil
而不是
。根据数学规则,四舍五入总是向上取整,而不是向下/向上取整。

像这样吗

function roundup5(x) { return (x%5)?x-x%5+5:x }
问候
保罗

我来到这里是为了寻找类似的东西。 如果我的号码是-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 }
函数取整(x){返回x%5 40
// 42 => 40
// 43 => 45
// 44 => 45
// 45 => 45
// 46 => 45
// 47 => 45
// 48 => 50
// 49 => 50
// 50 => 50

//精确地取整

var round = function (value, precision) {
    return Math.round(value * Math.pow(10, precision)) / Math.pow(10, precision);
};
var round5 = (value, precision) => {
    return round(value * 2, precision) / 2;
}
//精确到5

var round = function (value, precision) {
    return Math.round(value * Math.pow(10, precision)) / Math.pow(10, precision);
};
var round5 = (value, precision) => {
    return round(value * 2, precision) / 2;
}
使用舍入的原因是预期输入可以是随机数

谢谢

const roundToNearest5 = x => Math.round(x/5)*5
这将把数字四舍五入到最接近的5。要始终四舍五入到最接近的5,请使用
Math.ceil
。同样,要始终四舍五入,请使用
Math.floor
而不是
Math.round
。 然后可以像调用其他函数一样调用此函数。例如

roundToNearest5(21)
将返回:

20

round5(5)
应该给5还是10?如何:将x除以5,四舍五入到最接近的整数(使用Math.ceil函数),然后乘以5?round5(5)我想Math.ceil只将小数取整为整数。好吧,这里它确实将小数取整为整数,@AmitErandole;)+1表示简洁高效……它将取整为10,对吗?:)我会在这个函数中添加另一个参数,表示“取整”,所以原始数字可以四舍五入到我们在函数调用中设置的任何值,而不仅仅是固定的5…我喜欢这个解决方案!我用一个闭包来实现它,以便根据需要方便地更改多重内联:
const roundToNearestMultipleOf=m=>n=>Math.round(n/m)*m
用法:
roundToNearestMultipleOf(5)(32)
ReferenceError:
int
未定义。可能您想要
parseInt
,但这不是必需的,因为
Math.floor
返回一个数字。这可以更简单地通过使用
Math.round
+1来完成,因为我需要一种方法来舍入到最接近的5。(OP要求舍入到下一个5(向上)因此,被接受的答案确实是正确的,@Oliver。)谢谢你的解决方案,我的独特情况需要一个不使用浮点数学,但可以使用模的总结。
20