Number.prototype.numberFormat = function(c, d, t){
var n = this,
c = isNaN(c = Math.abs(c)) ? 2 : c,
d = d == undefined ? "." : d,
t = t == undefined ? "," : t,
s = n < 0 ? "-" : "",
i = String(parseInt(n = Math.abs(Number(n) || 0).toFixed(c))),
j = (j = i.length) > 3 ? j % 3 : 0;
return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};
使用方式也很簡單,參數分別如下:
- 1st: 小數點後有幾位 (超過的部分會四捨五入)
- 2nd: 小數點的符號
- 3rd: 千分位的符號
123456.789.numberFormat(2, '.', ',')
輸出的結果會是: 123,456.79
若是要改掉逗號跟千分位的符號變成這樣
123456.789.numberFormat(2, '*', '#')
輸出結果就是: 123#456*79
方便又好用喔!