From 210dd0da67d209773f2dae5a0751cc15f23dec31 Mon Sep 17 00:00:00 2001 From: "lixuefei.1313" Date: Thu, 7 Sep 2023 11:34:14 +0800 Subject: [PATCH] feat: support precision math of add & sub --- packages/vutils/__tests__/math/math.test.ts | 10 ++++++++++ packages/vutils/src/math.ts | 14 ++++++++++++++ 2 files changed, 24 insertions(+) create mode 100644 packages/vutils/__tests__/math/math.test.ts diff --git a/packages/vutils/__tests__/math/math.test.ts b/packages/vutils/__tests__/math/math.test.ts new file mode 100644 index 0000000..caae468 --- /dev/null +++ b/packages/vutils/__tests__/math/math.test.ts @@ -0,0 +1,10 @@ +import { precisionAdd, precisionSub } from '../../src/math'; + +describe('precision', () => { + it('precision add', () => { + expect(precisionAdd(0.1, 0.2)).toBe(0.3); + }); + it('precision sub', () => { + expect(precisionSub(33, 23.33)).toBe(9.67); + }); +}); diff --git a/packages/vutils/src/math.ts b/packages/vutils/src/math.ts index fe86ca7..816253e 100644 --- a/packages/vutils/src/math.ts +++ b/packages/vutils/src/math.ts @@ -117,3 +117,17 @@ export function fuzzyEqualVec(a: vec2, b: vec2): boolean { export function fixPrecision(num: number, precision = 10) { return Math.round(num * precision) / precision; } + +export function getDecimalPlaces(n: number): number { + const dStr = n.toString().split(/[eE]/); + const s = (dStr[0].split('.')[1] || '').length - (+dStr[1] || 0); + return s > 0 ? s : 0; +} + +export function precisionAdd(a: number, b: number) { + return fixPrecision(a + b, Math.pow(10, Math.max(getDecimalPlaces(a), getDecimalPlaces(b)))); +} + +export function precisionSub(a: number, b: number) { + return fixPrecision(a - b, Math.pow(10, Math.max(getDecimalPlaces(a), getDecimalPlaces(b)))); +}