Skip to content
12 changes: 12 additions & 0 deletions core/src/utils/floating-point/floating-point.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,24 @@ describe('floating point utils', () => {
const n = getDecimalPlaces(5);
expect(n).toBe(0);
});

it('should handle nullish values', () => {
expect(getDecimalPlaces(undefined as any)).toBe(0);
expect(getDecimalPlaces(null as any)).toBe(0);
expect(getDecimalPlaces(NaN as any)).toBe(0);
});
});

describe('roundToMaxDecimalPlaces', () => {
it('should round to the highest number of places as references', async () => {
const n = roundToMaxDecimalPlaces(5.12345, 1.12, 2.123);
expect(n).toBe(5.123);
});

it('should handle nullish values', () => {
expect(roundToMaxDecimalPlaces(undefined as any)).toBe(0);
expect(roundToMaxDecimalPlaces(null as any)).toBe(0);
expect(roundToMaxDecimalPlaces(NaN as any)).toBe(0);
})
});
});
4 changes: 4 additions & 0 deletions core/src/utils/floating-point/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { isSafeNumber } from '../type-guards.ts';

export function getDecimalPlaces(n: number) {
if (!isSafeNumber(n)) return 0;
if (n % 1 === 0) return 0;
return n.toString().split('.')[1].length;
}
Expand Down Expand Up @@ -36,6 +39,7 @@ export function getDecimalPlaces(n: number) {
* be used as a reference for the desired specificity.
*/
export function roundToMaxDecimalPlaces(n: number, ...references: number[]) {
if (!isSafeNumber(n)) return 0;
const maxPlaces = Math.max(...references.map((r) => getDecimalPlaces(r)));
return Number(n.toFixed(maxPlaces));
}
6 changes: 6 additions & 0 deletions core/src/utils/type-guards.ts
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can SafeNumber be defined by a fixed value or a fixed range of values,

For example,

0 and <0.00005
any input is number between 0 and 0.00005 to be defined and therefore handled as a "nullish value" and enable the rule to be applied if (!isSafeNumber(n)) return 0;

Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/**
* Checks input for usable number. Not NaN and not Infinite.
*/
export const isSafeNumber = (input: unknown): input is number => {
return typeof input === 'number' && !isNaN(input) && isFinite(input);
};
Loading