js 数字转汉字
时间: 2023-06-28 16:13:04 浏览: 88
数字转换汉字
5星 · 资源好评率100%
以下是 JavaScript 实现将数字转换为汉字的代码:
```javascript
function numberToChinese(num) {
if (isNaN(num)) return "";
const units = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
const unitChars = ["", "十", "百", "千"];
const bigUnitChars = ["", "万", "亿", "兆"];
let result = "";
let numStr = num.toString();
let len = numStr.length;
let zeroFlag = true;
let pos = 0;
while (len > 0) {
let cur = parseInt(numStr.charAt(pos));
let curChar = units[cur];
let unitChar = unitChars[len - 1];
if (cur === 0) {
if (!zeroFlag) {
result += curChar;
zeroFlag = true;
}
} else {
result += curChar + unitChar;
zeroFlag = false;
}
pos++;
len--;
if (len === 0 && pos < numStr.length) {
let bigUnitChar = bigUnitChars[Math.ceil(pos / 4)];
result += bigUnitChar;
len = numStr.length - pos;
}
}
return result;
}
```
使用方法:
```javascript
console.log(numberToChinese(123456789)); // 输出:一亿二千三百四十五万六千七百八十九
```
阅读全文