Add regression tests for 亿到元段间零填充。 Co-authored-by: Cursor <cursoragent@cursor.com>
88 lines
1.9 KiB
TypeScript
88 lines
1.9 KiB
TypeScript
export function toRmbUpper(value: number | null | undefined): string {
|
|
if (value == null || !Number.isFinite(value) || value < 0) {
|
|
return ''
|
|
}
|
|
|
|
if (value > 999999999999.99) {
|
|
return '金额过大'
|
|
}
|
|
|
|
const fen = Math.round(value * 100)
|
|
if (fen === 0) {
|
|
return '零元整'
|
|
}
|
|
|
|
const digits = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
|
|
const units = ['', '拾', '佰', '仟']
|
|
|
|
function sectionToChinese(n: number): string {
|
|
if (n === 0) return ''
|
|
let result = ''
|
|
let zeroPending = false
|
|
for (let i = 0; i < 4; i++) {
|
|
const digit = Math.floor(n / 10 ** (3 - i)) % 10
|
|
if (digit === 0) {
|
|
if (result !== '') {
|
|
zeroPending = true
|
|
}
|
|
} else {
|
|
if (zeroPending) {
|
|
result += '零'
|
|
zeroPending = false
|
|
}
|
|
result += digits[digit] + units[3 - i]
|
|
}
|
|
}
|
|
return result
|
|
}
|
|
|
|
const yuan = Math.floor(fen / 100)
|
|
const jiao = Math.floor((fen % 100) / 10)
|
|
const fenDigit = fen % 10
|
|
|
|
let result = ''
|
|
|
|
if (yuan > 0) {
|
|
const yi = Math.floor(yuan / 100000000)
|
|
const wan = Math.floor(yuan / 10000) % 10000
|
|
const rest = yuan % 10000
|
|
|
|
if (yi > 0) {
|
|
result += sectionToChinese(yi) + '亿'
|
|
}
|
|
if (wan > 0) {
|
|
if (yi > 0 && wan < 1000) {
|
|
result += '零'
|
|
}
|
|
result += sectionToChinese(wan) + '万'
|
|
}
|
|
if (rest > 0) {
|
|
if (wan > 0) {
|
|
if (rest < 1000) {
|
|
result += '零'
|
|
}
|
|
} else if (yi > 0) {
|
|
result += '零'
|
|
}
|
|
result += sectionToChinese(rest)
|
|
}
|
|
result += '元'
|
|
}
|
|
|
|
if (jiao > 0) {
|
|
result += digits[jiao] + '角'
|
|
} else if (fenDigit > 0 && yuan > 0) {
|
|
result += '零'
|
|
}
|
|
|
|
if (fenDigit > 0) {
|
|
result += digits[fenDigit] + '分'
|
|
}
|
|
|
|
if (jiao === 0 && fenDigit === 0) {
|
|
result += '整'
|
|
}
|
|
|
|
return result
|
|
}
|