价格转换工具函数
摘要:使用方法 parsePrice('19703000' // 19,703,000 parsePrice('19703000', true // 壹仟玖佰柒拾万叁仟 代码实现 // 价格格式化 export function parsePrice(price, toChinese = false { if (price == null || price === '' || isNaN(price retur<!--autointro-->...
使用方法
parsePrice('19703000') // 19,703,000
parsePrice('19703000', true) // 壹仟玖佰柒拾万叁仟
代码实现
// 价格格式化
export function parsePrice(price, toChinese = false) {
if (price == null || price === '' || isNaN(price)) return '';
if (!toChinese) {
return Number(price).toLocaleString('en-US');
}
// 中文大写数字
const cnNums = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
const cnIntRadice = ['', '拾', '佰', '仟'];
const cnIntUnits = ['', '万', '亿'];
let num = Number(price);
if (num === 0) return cnNums[0];
let str = '';
let unitPos = 0;
let needZero = false;
function sectionToChinese(section) {
let strIns = '', chnStr = '';
let unitPos = 0;
let zero = true;
while (section > 0) {
let v = section % 10;
if (v === 0) {
if (!zero) {
zero = true;
chnStr = cnNums[0] + chnStr;
}
} else {
zero = false;
strIns = cnNums[v] + cnIntRadice[unitPos];
chnStr = strIns + chnStr;
}
unitPos++;
section = Math.floor(section / 10);
}
return chnStr;
}
let integerNum = Math.floor(num);
let unitCount = 0;
while (integerNum > 0 && unitCount < cnIntUnits.length) {
let section = integerNum % 10000;
if (section !== 0) {
let sectionChinese = sectionToChinese(section);
if (needZero) {
str = cnNums[0] + str;
}
str = sectionChinese + cnIntUnits[unitCount] + str;
needZero = section < 1000 && section > 0;
} else {
needZero = true;
}
integerNum = Math.floor(integerNum / 10000);
unitCount++;
}
// 去除多余的零
str = str.replace(/零+/g, '零');
str = str.replace(/零(万|亿)/g, '$1');
str = str.replace(/亿万/, '亿');
str = str.replace(/零+$/, '');
return str;
}
本文链接:https://blog.smallhao.fun/?id=36 转载需授权!
Chen’Blog版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!