我在使用 toFixed 的 JavaScript 中遇到四舍五入小数的问题。
const num1 = (100.555).toFixed(2) // "100.56"
const num2 = (10.555).toFixed(2) // "10.55"
谁能解释为什么会发生这种行为?为什么第一个示例将小数点四舍五入为 56 而第二个示例将其四舍五入为 55?
更新: 如果我添加 4 位小数,则舍入不同。
const num3 = (10.5555).toFixed(2) // "10.56"
最佳答案
这应该可以解决您的问题
// its a rounding bug it can be compenstated by representing numbers exactly in decimal notation.
Number.prototype.toFixedDown = function(digits) {
var re = new RegExp("(\\d+\\.\\d{" + digits + "})(\\d)"),
m = this.toString().match(re);
return m ? parseFloat(m[1]) : this.valueOf();
};
const num1 = 100.555.toFixedDown(2)
const num2 = (10.555).toFixedDown(2)
alert(num1+ ' ' + num2);
关于使用 toFixed 的 javaScript 四舍五入小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61445787/