我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
当前回答
以下是最简短完整的答案:
function round(num, decimals) {
var n = Math.pow(10, decimals);
return Math.round( (n * num).toFixed(decimals) ) / n;
};
这还考虑了示例情况1.005,它将返回1.01。
其他回答
这里找到的答案都不正确。臭柴塞曼要求四舍五入,但你们都四舍五进。
要进行汇总,请使用以下命令:
Math.ceil(num * 100)/100;
var roundUpto = function(number, upto){
return Number(number.toFixed(upto));
}
roundUpto(0.1464676, 2);
toFixed(2):这里2是我们要舍入的位数。
这对正数、负数和大数都适用:
function Round(value) {
const neat = +(Math.abs(value).toPrecision(15));
const rounded = Math.round(neat * 100) / 100;
return rounded * Math.sign(value);
}
//0.244 -> 0.24
//0.245 -> 0.25
//0.246 -> 0.25
//-0.244 -> -0.24
//-0.245 -> -0.25
//-0.246 -> -0.25
它可能对你有用,
Math.round(num * 100)/100;
了解toFixed和round之间的区别。您可以查看Math.round(num)vs num.toFixed(0)和浏览器不一致性。
尝试此轻量级解决方案:
function round(x, digits){
return parseFloat(x.toFixed(digits))
}
round(1.222, 2);
// 1.22
round(1.222, 10);
// 1.222