Skip to content

Commit

Permalink
feat: support precision math of add & sub
Browse files Browse the repository at this point in the history
  • Loading branch information
xuefei1313 committed Sep 7, 2023
1 parent 0e4cf12 commit 210dd0d
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
10 changes: 10 additions & 0 deletions packages/vutils/__tests__/math/math.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
14 changes: 14 additions & 0 deletions packages/vutils/src/math.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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))));
}

0 comments on commit 210dd0d

Please sign in to comment.