js 阿拉伯数字转换中文数字
时间: 2023-10-01 20:03:41 浏览: 197
可以使用以下代码将阿拉伯数字转换为中文数字:
```javascript
function numberToChinese(num) {
var cnNums = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
var cnIntUnits = ["", "万", "亿", "万亿"];
var cnIntRadice = ["", "十", "百", "千"];
var cnDecUnits = ["角", "分", "毫", "厘"];
var cnIntLast = "元";
var maxNum = 999999999999999.9999;
var integerNum;
var chineseStr = "";
var parts;
if (num === "") {
return "";
}
num = parseFloat(num);
if (num >= maxNum) {
return "";
}
if (isNaN(num)) {
return "";
}
integerNum = Math.floor(num);
if (integerNum === 0) {
chineseStr = cnNums[0] + cnIntLast;
return chineseStr;
}
var intStr = integerNum.toString();
var len = intStr.length;
var i, j;
if (len > 15) {
return "";
}
parts = new Array(len);
for (i = 0; i < len; i++) {
parts[i] = parseInt(intStr.charAt(i), 10);
}
var partLen = Math.ceil(len / 4);
var partChinese;
for (i = 0; i < partLen; i++) {
partChinese = "";
for (j = 0; j < 4; j++) {
if (parts[i * 4 + j] === 0) {
continue;
}
partChinese += cnNums[parts[i * 4 + j]] + cnIntRadice[4 - j - 1];
}
partChinese += cnIntUnits[partLen - i - 1];
chineseStr += partChinese;
}
if (num.toString().indexOf(".") !== -1) {
var decNum = num.toString().split(".")[1];
var decLen = decNum.length;
for (i = 0; i < decLen; i++) {
if (i > 3) {
break;
}
chineseStr += cnNums[parseInt(decNum.charAt(i), 10)] + cnDecUnits[i];
}
}
if (chineseStr === "") {
chineseStr += cnNums[0] + cnIntLast;
} else if (num < 1) {
chineseStr = cnNums[0] + chineseStr;
}
return chineseStr;
}
```
使用示例:
```javascript
console.log(numberToChinese(123456789)); // 一亿二千三百四十五万六千七百八十九元
console.log(numberToChinese(100000001)); // 一亿零一元
console.log(numberToChinese(0.5)); // 五角
```
阅读全文