toFixed()方法bug

toFixed()方法bug

js中Number对象原生方法toFixed()存在bug,有时候无法正确将小数四舍五入进位输出,可以使用下面的方法代替:
Number.prototype.ToFixed = function (n) {
    
    
  const factor = Math.pow(10, n);
  const roundedValue = Math.round(this * factor) / factor;
  return roundedValue.toFixed(n);
};
const num = 3.14159;
console.log(num.toFixedCustom(2)); // 输出 3.14
console.log(num.toFixedCustom(3)); // 输出 3.142

猜你喜欢

转载自blog.csdn.net/qq_45099813/article/details/132811216
今日推荐