1
0

currency.js 715 B

1234567891011121314151617181920212223
  1. const digitsRE = /(\d{3})(?=\d)/g
  2. export function currency (value, currency, decimals) {
  3. value = parseFloat(value)
  4. if (!isFinite(value) || (!value && value !== 0)) return ''
  5. currency = currency != null ? currency : '$'
  6. decimals = decimals != null ? decimals : 2
  7. var stringified = Math.abs(value).toFixed(decimals)
  8. var _int = decimals
  9. ? stringified.slice(0, -1 - decimals)
  10. : stringified
  11. var i = _int.length % 3
  12. var head = i > 0
  13. ? (_int.slice(0, i) + (_int.length > 3 ? ',' : ''))
  14. : ''
  15. var _float = decimals
  16. ? stringified.slice(-1 - decimals)
  17. : ''
  18. var sign = value < 0 ? '-' : ''
  19. return sign + currency + head +
  20. _int.slice(i).replace(digitsRE, '$1,') +
  21. _float
  22. }