阅读:18
function convertToChineseCurrency(amount) {
// 定义单位
const units = new Array("分", "角", "元", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿");
// 定义数字对应的中文
const nums = new Array("零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖");
// 特殊处理小数点后两位
amount = Math.round(amount * 100) / 100;
let strOutput = "";
let strUnit = "";
amount = amount.toString();
let strReverse = "";
// 将数字部分和小数部分分离
let integerPart = '';
let decimalPart = '';
if (amount.indexOf('.') != -1) {
integerPart = amount.substring(0, amount.indexOf('.'));
decimalPart = amount.substring(amount.indexOf('.') + 1);
if (decimalPart.length == 1) {
decimalPart += '0'; // 确保小数部分有两位
}
} else {
integerPart = amount;
decimalPart = '00'; // 如果没有小数部分,则补零
}
// 反转整数部分字符串,方便从低位到高位处理
strReverse = integerPart.split("").reverse().join("");
console.log(strReverse);
// 处理整数部分
for (let i = 0; i < strReverse.length; i++) {
let tempStr = '';
let nIndex = parseInt(strReverse[i]);
if (nIndex != 0) {
tempStr = nums[nIndex] + units[i+2]; // 添加数字和单位
console.log( "nIndex:"+tempStr);
// 处理连续的零
if (i < strReverse.length - 1 && strReverse[i + 1] == '0') {
tempStr = ''; // 当前位为零,不添加到输出中
}
} else {
if (strOutput.indexOf('零') == -1 && strOutput != '') { // 避免连续多个零
tempStr = nums[nIndex]; // 只添加一个零
} else {
tempStr = ''; // 连续多个零,不添加到输出中
}
}
strOutput = tempStr + strOutput; // 将处理后的字符串添加到输出前面,以保持正确的顺序
}
// 处理小数部分,如果有的话
if (decimalPart != '00') {
strOutput += nums[parseInt(decimalPart[0])] + units[1] + nums[parseInt(decimalPart[1])] + units[0]; // 添加小数部分,包括“分”和“角”的单位
} else {
strOutput += '整'; // 如果没有小数部分,则添加“整”字
}
上一篇:html input、textarea监听粘贴图片 并上传 下一篇:echarts 中国地图动态加载数据(省市地区)展示
在线咨询