function amountToChinese(amount) {
if (typeof amount !== 'number' && typeof amount !== 'string') {
return '输入金额格式不正确';
}
amount = String(amount);
if (!/^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/.test(amount)) {
return '输入金额格式不正确';
}
const unit = '仟佰拾亿仟佰拾万仟佰拾元角分';
const str = '零壹贰叁肆伍陆柒捌玖';
let newAmount = amount.replace(/^0+/, '');
if (newAmount === '') {
return '零元整';
}
let fraction = '';
if (newAmount.indexOf('.') !== -1) {
const parts = newAmount.split('.');
newAmount = parts[0];
fraction = parts[1];
if (fraction.length === 1) {
fraction += '0';
}
} else {
fraction = '00';
}
let chineseStr = '';
let unitIndex = unit.length - 1;
for (let i = newAmount.length - 1; i >= 0; i--) {
if (newAmount[i] === '0') {
if (chineseStr.charAt(0) !== '零') {
chineseStr = '零' + chineseStr;
}
} else {
chineseStr = str.charAt(parseInt(newAmount[i])) + unit.charAt(unitIndex) + chineseStr;
}
unitIndex--;
}
chineseStr = chineseStr.replace(/零(仟|佰|拾|角)/g, '零').replace(/(零)+/g, '零');
chineseStr = chineseStr.replace(/零(万|亿)/g, '$1');
chineseStr = chineseStr.replace(/亿万/g, '亿');
chineseStr = chineseStr.replace(/^零+/g, '');
chineseStr = chineseStr.replace(/零元/, '元');
chineseStr = chineseStr.replace(/零角零分$/, '整');
chineseStr = chineseStr.replace(/零[整角分]+/, '整');
chineseStr = chineseStr.replace(/零角/, '零');
chineseStr = chineseStr.replace(/零分/, '');
chineseStr = chineseStr.replace(/元整/, '元');
if (fraction !== '00') {
chineseStr += str.charAt(parseInt(fraction[0])) + '角';
if (fraction[1] !== '0') {
chineseStr += str.charAt(parseInt(fraction[1])) + '分';
}
} else if (!chineseStr.includes('元')) {
chineseStr += '元整';
} else if (!chineseStr.endsWith("整")){
chineseStr += '整';
}
return chineseStr;
}
console.log(amountToChinese(1234567890.12));
console.log(amountToChinese(0.12));
console.log(amountToChinese(100000000));
console.log(amountToChinese(100000000.00));
console.log(amountToChinese(0));
console.log(amountToChinese(0.0));
console.log(amountToChinese("0"));
console.log(amountToChinese("0.0"));
console.log(amountToChinese("0.00"));
console.log(amountToChinese(100));
console.log(amountToChinese(100.00));
console.log(amountToChinese(100.1));
console.log(amountToChinese(1
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通