js中数字的toFixed在舍位的时候不是四舍五入的规则,在项目中不能符合要求,借鉴了decimal-format的内容,写了一个新的toFixed方法。
// 如果是小数,小数后面增加一个1,这样末位是5也能进位后舍去了
function adjust(n: number, scale: number) {
const num = n.toString();
if (num.includes('.')) {
const arr = num.split('.');
arr[1] = `${arr[1].padEnd(scale, '0')}1`;
return +arr.join('.');
}
/* istanbul ignore next */
return n;
}
// 纠正toFixed的四舍五入精度问题
export function toFixedCorrect(n: number, scale: number): string {
return (+adjust(n, scale)).toFixed(scale);
}