四舍五入toFixed

203 阅读1分钟
Number.prototype.toFixed = function (len) {
    var str = this + "";
    if (this >= 0) {
        s = Math.floor(this * Math.pow(10, len)) + ((str.substr(str.indexOf(".") + len + 1, 1)) >= 5 ? 1 : 0);
    } else {
        s = Math.floor(this * Math.pow(10, len)) + 1 + ((str.substr(str.indexOf(".") + len + 1, 1)) >= 5 ? -1 : 0);
    }
    return s / Math.pow(10, len);
}

console.log(1.335.toFixed(2)); //1.34