方法一:使用正则表达式
//方法一:使用正则表达式 function dealBigMoney(money) { if (money === '' || money == null || money === 'undefined') { return; } if (!/^(0|[1-9]\d*)(\.\d+)?$/.test(money)) { return "数据非法"; } money = money * 1.0; if (money === 0) { return "零"; } var unit = "仟佰拾亿仟佰拾万仟佰拾元角分", str = ""; money += "00"; var point = money.indexOf('.'); if (point >= 0) { money = money.substring(0, point) + money.substr(point + 1, 2); } unit = unit.substr(unit.length - money.length); for (var i = 0; i < money.length; i++) { str += '零壹贰叁肆伍陆柒捌玖'.charAt(money.charAt(i)) + unit.charAt(i); } var result = str.replace(/零(仟|佰|拾|角)/g, "零").replace(/(零)+/g, "零").replace(/零(万|亿|元)/g, "$1").replace(/(亿)万/g, "$1$2").replace(/^元零?|零分/g, "").replace(/元$/g, "元整"); return result; }View Code 方法二:常规JavaScript实现
//方法二:常规JavaScript实现 function dealBigMoney(money) { let fraction = ['角', '分']; let digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']; let unit = [['元', '万', '亿'], ['', '拾', '佰', '仟']]; let head = money < 0 ? '欠' : ''; money = Math.abs(money); let s = ''; for (let i = 0; i < fraction.length; i++) { s += (digit[Math.floor(money * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, ''); } s = s || '整'; money = Math.floor(money); for (let i = 0; i < unit[0].length && money > 0; i++) { let p = ''; for (let j = 0; j < unit[1].length && money > 0; j++) { p = digit[money % 10] + unit[1][j] + p; money = Math.floor(money / 10); } s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s; } return head + s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整'); }View Code
原文:https://blog.csdn.net/weixin_41937552/article/details/119996197
标签:money,JavaScript,金额,replace,length,let,Math,小写,unit From: https://www.cnblogs.com/daytoy105/p/16719955.html