const priceNum = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
function getPriceStr(price) {
const priceMinType = ['', '拾', '佰', '仟'];
const temFirstStrArr = price.split('');
temFirstStrArr.reverse();
const temStrArr = temFirstStrArr.map((item, index) => {
if (+item) {
return priceNum[+item] + priceMinType[index];
}
return priceNum[+item];
});
temStrArr.reverse();
return temStrArr.join('').replace(/零+/g, '零').replace(/零$/, '');
}
function priceTransform(price) {
// '':为了能够识别1000亿
const priceBigType = ['元', '万', '亿', ''];
const priceInt = parseInt(price);
const typeCount = parseInt(String(priceInt).length / 4);
const remainderCount = String(priceInt).length % 4;
if (typeCount > priceBigType.length - 2 && remainderCount > 0) {
return `最大单位为${priceBigType[priceBigType.length - 2]}`;
}
let strLast = '整';
// 角分
if (priceInt !== price) {
const priceLastType = ['角', '分'];
const lastPrice = /\.(\d{1,2})/.exec(price)[1];
const lastStrArr = lastPrice.split('');
const temStrArr = lastStrArr.map((item, index) => {
if (+item) {
return priceNum[+item] + priceLastType[index];
}
return '';
});
strLast = temStrArr.join('');
}
let strFirst = '';
let count = 0;
while (count <= typeCount) {
const sindex = (remainderCount + (count - 1) * 4) < 0 ? 0 : (remainderCount + (count - 1) * 4);
const eindex = remainderCount + count * 4;
const temNum = String(priceInt).substring(sindex, eindex);
strFirst += getPriceStr(temNum) ? getPriceStr(temNum) + priceBigType[typeCount - count] : '';
count++;
}
return strFirst + strLast;
}
console.log(priceTransform(1283.12)) // 壹仟贰佰捌拾叁元壹角贰分