首页 > 解决方案 > javaScript 使用 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"

标签: javascriptmathroundingtofixed

解决方案


这应该可以解决您的问题

// 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);


推荐阅读