Skip to content

Commit

Permalink
Add specific error when a e-notation number gets passed
Browse files Browse the repository at this point in the history
  • Loading branch information
bpierre committed May 15, 2023
1 parent 6bbbad6 commit 680f4ad
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/dnum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,13 @@ export function from(

value = String(value);

if (value.includes("e")) {
throw new Error(
`The passed number lost its precision: ${value}. `
+ `Please use a string, BigInt or Dnum value instead.`,
);
}

if (!value.match(NUM_RE)) {
throw new Error(`Incorrect number: ${value}`);
}
Expand Down
7 changes: 7 additions & 0 deletions test/all.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -624,6 +624,13 @@ describe("from()", () => {
it("works with numbers", () => {
expect(from(12345.29387, 18)).toEqual([12345293870000000000000n, 18]);
expect(from(-12345.29387, 18)).toEqual([-12345293870000000000000n, 18]);
expect(from(10 ** 20, 0)).toEqual([100000000000000000000n, 0]);
});
it("fails when the passed number lost its precision", () => {
expect(() => from(10 ** 21, 0))
.toThrowErrorMatchingInlineSnapshot(
'"The passed number lost its precision: 1e+21. Please use a string, BigInt or Dnum value instead."',
);
});
it("works with bigints", () => {
expect(from(1234529387n, 18)).toEqual([1234529387000000000000000000n, 18]);
Expand Down

0 comments on commit 680f4ad

Please sign in to comment.