diff --git a/src/index.ts b/src/index.ts index 4e5f509..6f48e3a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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; diff --git a/test/index.test.ts b/test/index.test.ts index 197daf7..bab3f1b 100644 --- a/test/index.test.ts +++ b/test/index.test.ts @@ -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); });