number-precision
number-precision copied to clipboard
希望能在运算效率上再加强
我做了一下压力测试,感觉效率上有改进的余地:
describe('求余数运算', () => {
//Math.round 用时14ms it('test Math', () => { let total=0; for (let i = 1; i <= 10000 * 10; i++) { total += Math.round(i * 100) / 100; } console.log(total); });
//Math.round 再加上求精度,转浮点数,用时 273ms it('test Math2', () => { let total=0; for (let i = 1; i <= 10000 * 10; i++) { total += Math.round(parseFloat((i * 100).toPrecision(14))) / 100; } console.log(total); });
//NP.round 用时1sec963ms
it('test NP', () => {
let total=0;
for (let i = 1; i <= 10000 * 10; i++) {
total += NP.round(i ,2) ;
}
console.log(total);
});
})
我利用空余时间也写了一个: function extendNumDoubles(n: number, timesNum: number): number { let s = n.toString(); let index = s.indexOf('.'); if (index === -1) return Number(s + '0'.repeat(timesNum)); else { let strLen = s.length; let numPointPos = index + 1 + timesNum;
let s2 =
s.slice(0, index) + //小数点前的数字
s.slice(index + 1, numPointPos) +//原小数点后和新小数点前的数字
(numPointPos <= strLen ? '.' : '') + //新小数点
s.slice(numPointPos) + //新小数点后的数字
(numPointPos - strLen > 0 ? '0'.repeat(numPointPos - strLen) : ''); //补零
return parseFloat(s2);
}
}
function toDecimalRound(x: number, digit: number): number { digit = Math.abs(digit); return Math.round(extendNumDoubles(Number(x.toPrecision(13)), digit)) / Math.pow(10, digit); }
用了268ms的时间: it('test Math toDecimalRound 268ms', () => { let total = 0; for (let i = 1; i <= 10000 * 10; i++) { total += toDecimalRound(i,2); } console.log(total); });