sd-chinese-currency.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // 格式化大写金额
  2. // 向右移位
  3. function shiftRight(number, digit) {
  4. digit = parseInt(digit, 10)
  5. const value = number.toString().split('e')
  6. return +(value[0] + 'e' + (value[1] ? +value[1] + digit : digit))
  7. }
  8. // 向左移位
  9. function shiftLeft(number, digit) {
  10. digit = parseInt(digit, 10)
  11. const value = number.toString().split('e')
  12. return +(value[0] + 'e' + (value[1] ? +value[1] - digit : -digit))
  13. }
  14. function sdChineseCurrency(n) {
  15. const fraction = ['角', '分']
  16. const digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
  17. const unit = [
  18. ['元', '万', '亿'],
  19. ['', '拾', '佰', '仟'],
  20. ]
  21. const head = n < 0 ? '欠' : ''
  22. n = Math.abs(n)
  23. let s = ''
  24. for (let i = 0; i < fraction.length; i++) {
  25. s += (digit[Math.floor(shiftRight(n, 1 + i)) % 10] + fraction[i]).replace(/零./, '')
  26. }
  27. s = s || '整'
  28. n = Math.floor(n)
  29. for (let i = 0; i < unit[0].length && n > 0; i++) {
  30. let p = ''
  31. for (let j = 0; j < unit[1].length && n > 0; j++) {
  32. p = digit[n % 10] + unit[1][j] + p
  33. n = Math.floor(shiftLeft(n, 1))
  34. }
  35. s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s
  36. }
  37. return (
  38. head +
  39. s
  40. .replace(/(零.)*零元/, '元')
  41. .replace(/(零.)+/g, '零')
  42. .replace(/^整$/, '零元整')
  43. )
  44. }
  45. export default sdChineseCurrency