Commit 3cb52223 authored by sunguoshu's avatar sunguoshu

update

parent 561b58ab
const digits = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'] as const
const units = ['', '拾', '佰', '仟'] as const
const units2 = ['', '万', '亿'] as const
const units3 = ['角', '分', '厘'] as const
export default function numberToWords(input: string | number): string {
const number = Number(input)
if (number >= 10 ** 13) throw new Error('数字太大')
if (number < 0) throw new Error('数字不能为负数')
if (number === 0) return '零元整'
let [integer = '', decimal = ''] = String(number).split('.')
integer = integer.padStart(12, '0').slice(-12)
decimal = decimal.padEnd(2, '0').slice(0, 2)
let result = ''
if (integer) {
let preNull = true
let zero = false
let blank = true
for (let i = 0; i < integer.length; i++) {
const j = integer.length - i - 1
const bit1 = units[j % 4]
const bit2 = units2[Math.floor(j / 4)]
const digit = digits[Number(integer[i])]
if (digit === '零') {
if (preNull) continue
zero = true
}
if (j % 4 === 3) blank = true
if (digit !== '零') {
preNull = false
blank = false
if (zero) {
zero = false
result += '零'
}
result += digit + bit1
}
if (j % 4 === 0 && !blank) result += bit2
}
}
if (result) result += '元'
if (!decimal || decimal === '00') return result + '整'
if (decimal) {
for (let i = 0; i < decimal.length; i++) {
const digit = digits[Number(decimal[i])]
if (result && i === 0 && digit === '零') {
result += '零'
}
if (digit !== '零') {
result += digit + units3[i]
}
}
}
return result
}
......@@ -2,6 +2,9 @@ import { describe, it, expect } from 'vitest'
import numberToWords from '../../src/money/numberToWords'
describe('测试整数', () => {
it('0 toBe 零元整', () => {
expect(numberToWords(0)).toBe('零元整')
})
it('1 toBe 壹元整', () => {
expect(numberToWords(1)).toBe('壹元整')
})
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment