Skip to content

Commit

Permalink
Merge pull request #35 from xiaosu12138/fix-negative
Browse files Browse the repository at this point in the history
feat: 修复负数四舍五入有误的问题
  • Loading branch information
camsong authored May 23, 2021
2 parents 44f82b8 + 04b4dc5 commit b1bde33
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,11 @@ function divide(num1: numType, num2: numType, ...others: numType[]): number {
*/
function round(num: numType, ratio: number): number {
const base = Math.pow(10, ratio);
return divide(Math.round(times(num, base)), base);
let result = divide(Math.round(Math.abs(times(num, base))), base);
if (num < 0 && result !== 0) {
result = times(result, -1);
}
return result;
}

let _boundaryCheckingState = true;
Expand Down
13 changes: 13 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -248,4 +248,17 @@ test('NP.round can do round operation', (t) => {
t.true(NP.round('1.2345e3', 3) === 1234.5);
t.true(NP.round('1.2344e3', 3) === 1234.4);
t.true(NP.round('1e3', 1) === 1000);

t.true(NP.round('-0.125', 2) === -0.13);
t.true(NP.round('-0.001', 2) === 0.00);
t.true(NP.round('-0.005', 2) === -0.01);
t.true(NP.round('0.125', 2) === 0.13);
t.true(NP.round('0.001', 2) === 0.00);
t.true(NP.round('0.005', 2) === 0.01);
t.true(NP.round(-0.125, 2) === -0.13);
t.true(NP.round(-0.001, 2) === 0.00);
t.true(NP.round(-0.005, 2) === -0.01);
t.true(NP.round(0.125, 2) === 0.13);
t.true(NP.round(0.001, 2) === 0.00);
t.true(NP.round(0.005, 2) === 0.01);
});

0 comments on commit b1bde33

Please sign in to comment.