js 数字转汉字
时间: 2023-06-28 10:13:04 浏览: 48
以下是 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)); // 输出:一亿二千三百四十五万六千七百八十九
```
相关推荐
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)