/*
*@Description: 给一个数值截取指定位数(不足补0,超出四舍五入),并返回添加指定前缀的字符串
*@params: currency 当前值
*@params: pre 前缀
*@params: precision 截取/补全位数
*@Return: return 新字符串
*/
function currencyFormatter(currency, pre = '', precision = 2) {
if (currency !== undefined && currency !== null) {
currency = currency.toString().replace(/\$|,/g, '');
}
// 检查传入数值为数值类型
if (isNaN(currency) || currency === '' || currency === null) {
return '';
}
// 获取符号(正/负数)
const sign = currency * 1 === (currency = Math.abs(currency));
currency = Math.floor(currency * Math.pow(10, precision) + 0.50000000001); // 把指定的小数位先转换成整数.多余的小数位四舍五入
let cents = currency % Math.pow(10, precision); // 求出小数位数值
currency = Math.floor(currency / Math.pow(10, precision)).toString(); // 求出整数位数值
if (precision !== 0) {
cents = cents.toString(); // 把小数位转换成字符串,以便求小数位长度
// 补足小数位到指定的位数
while (cents.length < precision) {
cents = '0' + cents;
}
cents = '.' + cents;
} else {
cents = '';
}
if (currency) {
currency = thousandthFormatter(currency);
}
return pre + ((sign ? '' : '-') + currency + cents);
}
function thousandthFormatter(value) {
let currency = value + '';
let result = 0;
if (currency) {
// 对整数部分进行千分位格式化.
for (let i = 0; i < Math.floor((currency.length - (1 + i)) / 3); i++) {
currency =
currency.substring(0, currency.length - (4 * i + 3)) +
',' +
currency.substring(currency.length - (4 * i + 3));
}
result = currency;
}
return result;
}
console.log(currencyFormatter(-123.3089,'#',3))
console