broken toFixed implementation

后端 未结 6 2226
陌清茗
陌清茗 2020-11-27 21:51

The default implementation of javascript\'s \"Number.toFixed\" appears to be a bit broken.

console.log((8.555).toFixed(2));    // returns 8.56
console.log((         


        
6条回答
  •  广开言路
    2020-11-27 22:23

    Maybe it will help someone, this is fixed popular formatMoney() function, but with correct roundings.

    Number.prototype.formatMoney = function() {
      var n = this,
      decPlaces = 2,
      decSeparator = ",",
      thouSeparator = " ",
      sign = n < 0 ? "-" : "",
      i = parseInt(n = Math.abs(+n || 0)) + "",
      j = (j = i.length) > 3 ? j % 3 : 0,
      decimals = Number(Math.round(n +'e'+ decPlaces) +'e-'+ decPlaces).toFixed(decPlaces),
      result = sign + (j ? i.substr(0, j) + thouSeparator : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thouSeparator) + (decPlaces ? decSeparator + Math.abs(decimals-i).toFixed(decPlaces).slice(2) : "");
      return result;
    };
    
    (9.245).formatMoney(); // returns 9,25
    (7.5).formatMoney();   // returns 7,50
    (8.575).formatMoney(); // returns 8,58
    

提交回复
热议问题