Number.prototype.toLocaleString()

  1. (999999999).toLocaleString(); // 999,999,999
  2. // 还可以加参数,进行更优雅的做法
  3. const options = {
  4. style: 'currency',// style: 'currency'注释掉就没有 ¥ 符号
  5. currency: 'CNY',
  6. };
  7. (999999).toLocaleString('zh-CN', options); // ¥999,999.00

js实现

  1. export const moneyFormat = (number, decimals, dec_point, thousands_sep) => {
  2. number = (number + '').replace(/[^0-9+-Ee.]/g, '')
  3. const n = !isFinite(+number) ? 0 : +number
  4. const prec = !isFinite(+decimals) ? 2 : Math.abs(decimals)
  5. const sep = typeof thousands_sep === 'undefined' ? ',' : thousands_sep
  6. const dec = typeof dec_point === 'undefined' ? '.' : dec_point
  7. let s = ''
  8. const toFixedFix = function(n, prec) {
  9. const k = Math.pow(10, prec)
  10. return '' + Math.ceil(n * k) / k
  11. }
  12. s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.')
  13. const re = /(-?\d+)(\d{3})/
  14. while (re.test(s[0])) {
  15. s[0] = s[0].replace(re, '$1' + sep + '$2')
  16. }
  17. if ((s[1] || '').length < prec) {
  18. s[1] = s[1] || ''
  19. s[1] += new Array(prec - s[1].length + 1).join('0')
  20. }
  21. return s.join(dec)
  22. }
  23. moneyFormat(10000000) // 10,000,000.00
  24. moneyFormat(10000000, 3, '.', '-') // 10-000-000.000