Javascript随机十进制值后的四舍五入值
我想在一个随机的十进制值之后对这个值进行四舍五入Javascript随机十进制值后的四舍五入值,javascript,performance,math,rounding,Javascript,Performance,Math,Rounding,我想在一个随机的十进制值之后对这个值进行四舍五入 Example(round up when value > x.90): 18.25478 => 18 18.7545 => 18 18.90 => 19 18.95 = > 19 我知道Math.ceil和Math.Floor方法,但我想结合成一种方法。我还读到Math.floor和ceil的值太多,速度很慢(我将在列表中转换3000.000+个值!) 如何在JavaScript中实现这一点?您可以添加0.1并
Example(round up when value > x.90):
18.25478 => 18
18.7545 => 18
18.90 => 19
18.95 = > 19
我知道Math.ceil和Math.Floor方法,但我想结合成一种方法。我还读到Math.floor和ceil的值太多,速度很慢(我将在列表中转换3000.000+个值!)
如何在JavaScript中实现这一点?您可以添加
0.1
并使用Math.floor
函数轮(v){
返回数学楼层(v+0.1);
}
变量数组=[
18.25478, // => 18
18.7545, // => 18
18.90, // => 19
18.95, // => 19
];
console.log(array.map(round))
您可以添加0.1
并使用Math.floor
函数轮(v){
返回数学楼层(v+0.1);
}
变量数组=[
18.25478, // => 18
18.7545, // => 18
18.90, // => 19
18.95, // => 19
];
console.log(array.map(round))代码>您可以使用此功能:
function customRound(x) {
if (x - Math.floor(x) >= 0.9) {
return Math.ceil(x);
} else {
return Math.floor(x);
}
}
您可以使用此功能:
function customRound(x) {
if (x - Math.floor(x) >= 0.9) {
return Math.ceil(x);
} else {
return Math.floor(x);
}
}
如果您正在寻找一个更通用的答案,将自定义阈值作为输入,此函数将更好地满足您的需要。如果您担心Math.ceil()
和Math.floor()
,它也会使用Math.round()
。它还处理负数。你可以在这里摆弄它:
示例:
customRound(18.7545, 0.9) => 18
customRound(18.9, 0.9) => 19
如果您正在寻找一个更通用的答案,将自定义阈值作为输入,此函数将更好地满足您的需要。如果您担心Math.ceil()
和Math.floor()
,它也会使用Math.round()
。它还处理负数。你可以在这里摆弄它:
示例:
customRound(18.7545, 0.9) => 18
customRound(18.9, 0.9) => 19
以下是允许可变阈值的灵活功能
function roundWithThreshold(threshold, num) {
return Math[ num % 1 > threshold ? 'ceil' : 'floor' ](num);
}
用法:
roundWithThreshold(0.2, 4.4);
以下是允许可变阈值的灵活功能
function roundWithThreshold(threshold, num) {
return Math[ num % 1 > threshold ? 'ceil' : 'floor' ](num);
}
用法:
roundWithThreshold(0.2, 4.4);
你有负数吗?你有负数吗?