JavaScript 数字转千元符方法

1.方法一

// normal 参数是币种 币种等于 JPY 【日元】不显示千元符 默认显示千元符
function toThousands(num = 0, currency = 'normal', point = 2) {
  let newNum = String(num)
  var reg = new RegExp(',', 'g')
  if (newNum.indexOf(',') !== -1) {
    newNum = newNum.replace(reg, '')
  }
  let zero = '.00'
  if (newNum === 'null') {
    newNum = 0
  } else {
    newNum = Number(newNum)
  }
  if (currency === 'JPY') zero = ''
  var [sInt, sFloat] = (Number.isInteger(newNum) ? `${newNum}` : newNum.toFixed(point)).split('.')
  sInt = sInt.replace(/\d(?=(\d{3})+$)/g, '$&,')
  return sFloat ? `${sInt}.${sFloat}` : `${sInt}` + `${zero}`
}

2.方法二

toThousands(num) {
  let num = (num || 0).toString()
  let result = ''
  while (num.length > 3) {
    result = ',' + num.slice(-3) + result
    num = num.slice(0, num.length - 3)
  }
  if (num) { result = num + result }
  return result
}

 

posted @ 2020-12-16 10:30  皮一皮很开心  阅读(257)  评论(0编辑  收藏  举报