const digitChar = ['', ...'一二三四五六七八九']const posChar = ['', ...'十百千万 亿']const placeholder = '零'function toChineseNumeralUnder万(digits) { let revDigits = digits.split('').reverse() let result = '' for (let pos = 0; pos < revDigits.length; pos++) { const digit = Number(revDigits[pos]) if (digit) { result = posChar[pos] + result } if (digit !== 1 || pos !== 1) { result = digitChar[digit] + result } if (!digit && pos && result && !result.startsWith(placeholder)) { result = placeholder + result } } return result}function toChineseNumeralUnder亿(digits) { let highPart = toChineseNumeralUnder万(digits.slice(-8, -4)) if (highPart) { highPart += posChar[4] } let lowPart = toChineseNumeralUnder万(digits.slice(-4)) return highPart + lowPart}function toChineseNumeral(digits) { let fragment = '' const result = [] for (const digit of digits.split('').reverse()) { if (fragment.length === 8) { result.unshift(toChineseNumeralUnder亿(fragment)) fragment = '' } fragment = digit + fragment } result.unshift(toChineseNumeralUnder亿(fragment)) if (result[0].startsWith(placeholder)) { result[0] = result[0].slice(1) } return result.join(posChar[8]) || placeholder}toChineseNumeral('0')// => '零'toChineseNumeral('101')// => '一百零一'toChineseNumeral('1000001')// => '一百万零一'toChineseNumeral('123456708')// => '一亿二千三百四十五万六千七百零八'toChineseNumeral('3274823947329471041041234567080')// => '三百二十七万四千八百二十三亿九千四百七十三万二千九百四十七亿一千零四十一万零四百一十二亿三千四百五十六万七千零八十'
函数名很弱智,不要在意(
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)