1. 云栖社区>
2. >
3. 正文

JavaScript将数字转换为大写金额函数

var digitUppercase = function(n) {
var fraction = ['角', '分'];
var digit = [
'零', '壹', '贰', '叁', '肆',
'伍', '陆', '柒', '捌', '玖'
];
var unit = [
['元', '万', '亿'],
['', '拾', '佰', '仟']
];
var head = n < 0 ? '欠' : '';
n = Math.abs(n);
var s = '';
for (var i = 0; i < fraction.length; i++) {
s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
}
s = s || '整';
n = Math.floor(n);
for (var i = 0; i < unit[0].length && n > 0; i++) {
var p = '';
for (var j = 0; j < unit[1].length && n > 0; j++) {
p = digit[n % 10] + unit[1][j] + p;
n = Math.floor(n / 10);
}
s = p.replace(/(零.)*零\$/, '').replace(/^\$/, '零') + unit[0][i] + s;
}
return head + s.replace(/(零.)*零元/, '元')
.replace(/(零.)+/g, '零')
.replace(/^整\$/, '零元整');
};

console.log(digitUppercase(7682.01)); //柒仟陆佰捌拾贰元壹分
console.log(digitUppercase(7682));  //柒仟陆佰捌拾贰元整
console.log(digitUppercase(951434677682.00)); //玖仟伍佰壹拾肆亿叁仟肆佰陆拾柒万柒仟陆佰捌拾贰元整

// 将输入的数字金额转换成对应的中文大写金额
// idNumber输入的数字金额，idCHN输出的中文大写金额
function TransformNumberIntoCHN(idNumber, idCHN) {
var number = document.getElementById(idNumber).value;
if (!/^(0|[1-9]\d*)(\.\d{1,2})?\$/.test(number)) {
document.getElementById(idCHN).value = "";
document.getElementById(idNumber).value = "";
return false;
}
var unit = "仟佰拾亿仟佰拾万仟佰拾元角分", str = "";
number += "00";
var point = number.indexOf('.');
if (point >= 0) {
number = number.substring(0, point) + number.substr(point + 1, 2);
}
unit = unit.substr(unit.length - number.length);
for (var i = 0; i < number.length; i++) {
str += '零壹贰叁肆伍陆柒捌玖'.charAt(number.charAt(i)) + unit.charAt(i);
}
//document.getElementById(idCHN).value = str.replace(/零(仟|佰|拾|角)/g, "零").replace(/(零)+/g, "零").replace(/零(万|亿|元)/g, "\$1").replace(/(亿)万|壹(拾)/g, "\$1\$2").replace(/^元零?|零分/g, "").replace(/元\$/g, "元整");
document.getElementById(idCHN).value = str.replace(/零(仟|佰|拾|角)/g, "零").replace(/(零)+/g, "零").replace(/零(万|亿|元)/g, "\$1").replace(/(亿)万|(拾)/g, "\$1\$2").replace(/^元零?|零分/g, "").replace(/元\$/g, "元整");

40+云计算产品，6个月免费体验