Javascript 随机小数后的舍入值
Javascript round value after a random decimal value
我想将值四舍五入到一个随机小数值后
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
。
function round(v) {
return Math.floor(v + 0.1);
}
var array = [
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);
}
}
如果您正在寻找将您的自定义阈值作为输入的更通用的答案,此功能将更适合您的需求。如果您担心 Math.ceil()
和 Math.floor()
,它也会使用 Math.round()
。它还处理负数。您可以在此处 fiddle 使用它:https://jsfiddle.net/f0vt7ofw/
function customRound(num, threshold) {
if (num >= 0) {
return Math.round(num - (threshold - 0.5));
}
else {
return Math.round(num + (threshold - 0.5));
}
}
示例:
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);
我想将值四舍五入到一个随机小数值后
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
。
function round(v) {
return Math.floor(v + 0.1);
}
var array = [
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);
}
}
如果您正在寻找将您的自定义阈值作为输入的更通用的答案,此功能将更适合您的需求。如果您担心 Math.ceil()
和 Math.floor()
,它也会使用 Math.round()
。它还处理负数。您可以在此处 fiddle 使用它:https://jsfiddle.net/f0vt7ofw/
function customRound(num, threshold) {
if (num >= 0) {
return Math.round(num - (threshold - 0.5));
}
else {
return Math.round(num + (threshold - 0.5));
}
}
示例:
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);