一个实用的js函数,工作可以经常用到,上代码!
效果
代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<script>
function ChineseNumber() {
amount = document.getElementById("numb").value;
if (amount != '' && amount.substring(0, 1) == '-')
return "";
if (!/^\d*(\.\d*)?$/.test(amount)) {
$("input[id$=amount]").val("");
return "";
}
var AA = new Array("零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖");
var BB = new Array("", "拾", "佰", "仟", "万", "亿", "元", "");
var a = ("" + amount).replace(/(^0*)/g, "").split("."), k = 0, re = "";
for ( var i = a[0].length - 1; i >= 0; i--) {
switch (k) {
case 0:
re = BB[7] + re;
break;
case 4:
if (!new RegExp("0{4}\\d{" + (a[0].length - i - 1) + "}$")
.test(a[0]))
re = BB[4] + re;
break;
case 8:
re = BB[5] + re;
BB[7] = BB[5];
k = 0;
break;
}
if ((k % 4 == 2 || k % 4 == 3) && a[0].charAt(i + 2) != 0
&& a[0].charAt(i + 1) == 0)
re = AA[0] + re;
if ((k % 4 == 3) && a[0].charAt(i) == 0 && a[0].charAt(i + 1) != 0)
re = AA[0] + re;
if ((k % 4 == 3) && a[0].charAt(i - 1) == 0 && a[0].charAt(i) != 0) {
if (a[0].charAt(i - 2)) {
re = AA[0] + AA[a[0].charAt(i)] + BB[k % 4] + re;
} else {
re = AA[a[0].charAt(i)] + BB[k % 4] + re;
}
} else {
if (a[0].charAt(i) != 0) {
re = AA[a[0].charAt(i)] + BB[k % 4] + re;
}
}
k++;
}
if (a.length > 1) { // 加上小数部分(如果有小数部分)
if ((a[1].charAt(0) == 0) && (a[1].charAt(1) == 0)) {
re += BB[6];
re += "整";
} else {
if (re == "") {// 角是最高位
if (a[1].charAt(0) != "0") {// 角不为“零”
re += AA[a[1].charAt(0)];
re += "角";
}
} else {// 角不是最高位
re += BB[6];// 加上“元”
re += AA[a[1].charAt(0)];
if (a[1].charAt(0) != "0") {// 角不为零
re += "角";
}
}
if (a[1].charAt(1) != 0) {
re += AA[a[1].charAt(1)];
re += "分";
}
}
} else {
re += BB[6];
}
document.getElementById("demo").innerHTML = re;
}
</script>
<body>
<h1>数字金额转换中文</h1>
<p>请输入金额数字:</p>
<input id="numb">
<button type="button" onclick="ChineseNumber()">提交</button>
<p id="demo"></p>
</body>
</html>