From 04b4dc56e30bdf61920924bd01571858ce007dc0 Mon Sep 17 00:00:00 2001 From: suxiao Date: Sun, 28 Jun 2020 20:12:17 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E4=BF=AE=E5=A4=8D=E8=B4=9F=E6=95=B0?= =?UTF-8?q?=E5=9B=9B=E8=88=8D=E4=BA=94=E5=85=A5=E6=9C=89=E8=AF=AF=E7=9A=84?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/index.ts | 6 +++++- test/index.test.ts | 13 +++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) 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); });