You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
我利用空余时间也写了一个:
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;
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);
});
我做了一下压力测试,感觉效率上有改进的余地:
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);
});
})
The text was updated successfully, but these errors were encountered: