Max number value in JS
# Javascript
Hi guys👋. Recently I’ve worked on a backend project, where we need to store a number in database which is 19 digit length & unique across records.
I’ve written API’s, tested by entering a initial record everything is working perfect. While doing entry into database we’re following a number series.
8991754057201174837
8991754057201174838
8991754057201174839
8991754057201174840
Problem
First entry worked fine, but from second entry onwards we’re getting unique field constraint error. We’re sending unique value in API but still getting an error
I’ve checked the database entries, the last four digits got rounded 😵💫
| Id | Serial No |
|---|---|
| 1 | 8991754057201170000 |
- I’m sending proper payload to API, but still the number is rounded.
- Did a quick search found the max safe integer is
9007199254740991. Which is 16 digit length - Number greater than 16 digit it’ll get rounded.
8991754057201174838 -> 8991754057201170000
Solution
- We can use bigger number using
BigIntin JS. - But BigInt can’t be serialized error will’be thrown.
// Uncaught TypeError: Do not know how to serialize a BigInt
JSON.stringify({ serial_no: BigInt(number) });
- Final retreat was fallback to string field.
backend (accepts string "8991754057201174838" ) -> postgres database (converts to 8991754057201174838)
- Luckily we’ve used hasura which expose GraphQL API’s on postgres database, it took care of
casting (string -> number conversion)at database level. - Most of other languages has support for 20+ digit integers.
That’s it for this blog, hope this might help you in those scenario’s. Until next blog peace✌️