js 实现千亿范围内的数字转大写,支持小数点后四位
/**
* @description 千亿范围内的数字转大写,支持小数点后四位
* @param { Number } 要转换的数字
* @returns { String } 大写的数字
*/
export function moneyToCapital(val) {
let n = String(val);
if (n === '0') {
return '零';
}
if (!/^(0|[1-9]\d*)(\.\d+)?$/.test(n)) { return ''; }
let unit = '千百拾亿千百拾万千百拾元角分毫厘';
let str = '';
const p = n.indexOf('.');
if (p >= 0) {
const nList = n.split('.');
const iLen = nList[1].length;
for (let i = 4 - iLen; i > 0; i--) {
nList[1] += '0';
}
n = nList.join('');
} else {
n += '0000';
}
unit = unit.substring(unit.length - n.length);
for (let i = 0; i < n.length; i++) {
str += '零壹贰叁肆伍陆柒捌玖'.charAt(n.charAt(i)) + unit.charAt(i);
}
return str.replace(/零(千|百|拾|角|分|毫)/g, '零')
.replace(/(零)+/g, '零')
.replace(/零(万|亿|元)/g, '$1')
.replace(/(亿)万|壹(拾)/g, '$1$2')
.replace(/^元零?|零厘/g, '')
.replace(/元$/g, '元整')
.replace(/^厘$/g, '零');
}
/**
* in the end
* 我们正改变着我们的世界..
*/