很多人在用JS实现四舍五入的时候直接用tofixed 或 math.round 等方法都是不行的。要不会出现五不入,要不会出现四不舍的情况。
下面提供一个JS实现四舍五入的解决方法:
函数:
function round(num, decimal) {
if (isNaN(num)) {
return 0;
}
const num1 = Math.pow(10, decimal + 1);
const num2 = Math.pow(10, decimal);
const res = Math.round(num * num1 / 10) / num2;
return res.toFiexed(decimal);
}
console.log(round(23.235,2)) ==> 23.24
console.log(round(23.234,2)) ==> 23.23
这篇博客探讨了在JavaScript中使用toFixed()和Math.round()进行四舍五入操作时可能遇到的问题,如五不入和四不舍。作者提供了一个自定义函数`round(num, decimal)`来解决这个问题,确保四舍五入的准确性。该函数通过乘以适当倍数进行调整后再进行四舍五入,然后除回原倍数,从而得到正确的结果。
1202

被折叠的 条评论
为什么被折叠?



