使用 toFixed 的 javaScript 四舍五入小数

标签 javascript math rounding tofixed

我在使用 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/

相关文章:

javascript无法将数据重新分配给map()中的数组

javascript - 尽管 onClick 应该返回 false,但表单已提交

困惑为什么代码不能正确运行

php - 始终将小数四舍五入到指定精度

javascript - 从父窗口访问 iframe 中的 DOM 附加函数

javascript - 在移动浏览器中播放声音?

iphone - 如何在没有陀螺仪的设备上创建 CMRotationMatrix

math - AABB 与圆 - 反之亦然,使用分离轴定理

php - 如何使用此分页代码获取页面上的项目数?

java - 如果我将 long 数据类型分配给 float 数据类型,为什么会出现舍入错误?