tags: js

categories: js

JS数字格式转换为千分位

不使用正则表达式

  1. var num = 123456789;
  2. 1.格式化为千分位输出 num.toLocaleString()
  3. //"123,456,789"
  4. 2.格式化为千分位带$符号输出
  5. num.toLocaleString("en-US",{style:"currency",currency:"USD"})
  6. //"$123,456,789.00"
  7. 3.格式化为带¥符号输出
  8. num.toLocaleString("zh-Hans-CN",{style:"currency",currency:"CNY"})
  9. //"¥123,456,789.00"

使用正则表达式

  1. // 数字转换成货币格式 封装
  2. // number 数字
  3. // places 小数位
  4. // sybol 货币前缀
  5. // thousand 货币以什么分割
  6. // decimal 以什么跟小数分割
  7. // formatMoney(value, 2, "¥", ",", ".")
  8. const formatMoney = function (number, places, symbol, thousand, decimal) {
  9. places = !isNaN(places = Math.abs(places)) ? places : 2;
  10. symbol = symbol !== undefined ? symbol : "¥";
  11. thousand = thousand || ",";
  12. decimal = decimal || ".";
  13. if(number){
  14. var negative = number < 0 ? "-" : "",
  15. i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "",
  16. j = (j = i.length) > 3 ? j % 3 : 0;
  17. return symbol + negative + (j ? i.substr(0, j) + thousand : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousand) + (places ? decimal + (Math.abs(number - i).toFixed(places) + "").slice(2) : "");
  18. }else{
  19. return symbol + parseFloat(0).toFixed(places)
  20. }
  21. }