JS函数实现数字转中文大写
-
-
- 1. 数字转字符,分割,去除空字符
- 2. 遍历分割字符,替换为中文
- 3. 增加四位数单位
- 4. 处理零
- 5. 拼接四位数据和单位
项目中,JS将万亿以下正整数转为中文大写
1. 数字转字符,分割,去除空字符
function toChineseNumber(num){
const strs = num.toString().replace(/(?=(\d{4})+$)/g, ",")
.split(",").filter(Boolean);
console.log(strs);
}
toChineseNumber(41231234);
2. 遍历分割字符,替换为中文
function toChineseNumber(num){
const strs = num.toString().replace(/(?=(\d{4})+$)/g, ",")
.split(",").filter(Boolean);
const chinese = ['零','壹','贰','叁','肆','伍','陆','柒','捌','玖']
const unit = ['','拾','佰','仟']
function _transform(numStr){
let result = '';
for (let i = 0; i < numStr.length; i++) {
const digit = chinese[numStr[i]];
console.log(digit);
}
}
for (let i = 0; i < strs.length; i++) {
const part = strs[i];
_transform(part);
}
console.log(strs);
}
toChineseNumber(41231234);
3. 增加四位数单位
function _transform(numStr){
let result = '';
for (let i = 0; i < numStr.length; i++) {
const digit = chinese[numStr[i]];
const c = unit[numStr.length - 1 - i];
result += digit + c;
}
console.log(result);
}
4. 处理零
function _transform(numStr){
let result = '';
for (let i = 0; i < numStr.length; i++) {
const digit = chinese[numStr[i]];
const c = unit[numStr.length - 1 - i];
if(digit === '零'){
if(result[result.length-1] !== chinese[0]){
result += digit;
}
}else{
result += digit + c;
}
}
if(result[result.length-1] === chinese[0]){
result = result.slice(0, -1);
}
console.log(result);
}
5. 拼接四位数据和单位
function toChineseNumber(num){
const strs = num.toString().replace(/(?=(\d{4})+$)/g, ",")
.split(",").filter(Boolean);
const chinese = ['零','壹','贰','叁','肆','伍','陆','柒','捌','玖']
const unit = ['','拾','佰','仟']
function _transform(numStr){
let result = '';
for (let i = 0; i < numStr.length; i++) {
const digit = chinese[numStr[i]];
const c = unit[numStr.length - 1 - i];
if(digit === '零'){
if(result[result.length-1] !== chinese[0]){
result += digit;
}
}else{
result += digit + c;
}
}
if(result[result.length-1] === chinese[0]){
result = result.slice(0, -1);
}
return result;
}
let res = "";
const bigUnit = ['','万','亿'];
for (let i = 0; i < strs.length; i++) {
const part = strs[i];
res += _transform(part) ? _transform(part) + bigUnit[strs.length - i - 1] : _transform(part);
}
console.log(res);
console.log(strs);
}
toChineseNumber(402000000340);