money.js 428 B

123456789101112131415
  1. function money(s, n) {
  2. n = n || 0;
  3. n = n >= 0 && n <= 5 ? n : 2;
  4. s = parseFloat((s + '').replace(/[^\d\.-]/g, '')).toFixed(n) + '';
  5. s = s.split('.');
  6. let l = s[0].split('').reverse(),
  7. r = s[1] || '',
  8. t = '';
  9. for (let i = 0; i < l.length; i++) {
  10. t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? ',' : '');
  11. }
  12. return t.split('').reverse().join('') + (r ? ('.' + r) : r);
  13. }
  14. module.exports = money;