问题背景
要求实现一个金额转换的工具类,输入一个数字金额,返回它的大写金额。
例如:
输入:105
输出:壹佰零伍
输入:6543
输出:陆仟伍佰肆拾叁
代码实现
/**
* @description 数字金额转大写的金额的公共方法
* @author Joyce Lee
* @date 2024-06-17
* @param num 105
* @returns {string} 壹佰零伍
*/
export const convertToChineseCurrency = (num) => {
const digitToChinese = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"];
const unitToChinese = ["", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟"];
let numStr = num.toString();
let result = '';
let zeroFlag = false;
for (let i = numStr.length - 1; i >= 0; i--) {
let digit = parseInt(numStr.charAt(i));
if (digit !== 0) {
result = digitToChinese[digit] + unitToChinese[numStr.length - 1 - i] + result;
zeroFlag = false;
} else {
if (!zeroFlag && i != 0 && parseInt(numStr.charAt(i - 1)) > 0) {
result = digitToChinese[digit] + result;
zeroFlag = true;
}
}
}
return result;
}
测试
console.log(convertToChineseCurrency(105)) // 壹佰零伍
console.log(convertToChineseCurrency(6543)) // 陆仟伍佰肆拾叁
console.log(convertToChineseCurrency(17986)) // 壹万柒仟玖佰捌拾陆