I am trying to convert this "9876543210223023" into integer which is received as a string .I have used parseInt but it gets converted into 9876543210223024. This is causing failure in my validations . Please suggest how will the value remain same after conversion.
Asked
Active
Viewed 105 times
1
-
Take a read to [BigInt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt). Maybe that could help you... – Shidersz Feb 13 '19 at 17:41
-
1That number exceeds Number.MAX_SAFE_INTEGER so you cannot parse it as a precise integer. Do you need to perform arithmetic on it? (i.e. why does it need to b a number for validation) – Alex K. Feb 13 '19 at 17:41
-
@Shidersz `BigInt` isn't supported by Edge or Safari and in Firefox it's an experimental feature disabled by default, so that might not be a viable option for OP. – Abion47 Feb 13 '19 at 17:44
-
@AlexK. Yes.i need to perform comparison with other numbers – Divya G Feb 13 '19 at 17:48
-
What type of comparisons? for equality just keep everything as strings. – Alex K. Feb 13 '19 at 17:51
-
Greater and Less than other fields which is an integer – Divya G Feb 13 '19 at 18:04
1 Answers
1
9876543210223023 is > than 9007199254740991, which is Number.MAX_SAFE_INTEGER
.
JavaScript has a Number type, which internally is a 64 bit floating point number.
If the range is too big, the machine episilon is too large, and the number is rounded to the nearest representable number, in this case 9876543210223024.
You need a biginteger library, if you want to process numbers of this size.
If your browser is modern enough (aka Chrome/Chromium), it might have the type "BigInteger" already built-in.
In that case: BigInt("9876543210223023", 10)
Otherwise, the linked BigInt-library will act as polyfill.

Stefan Steiger
- 78,642
- 66
- 377
- 442
-
-
@Divya G: If you use BigInt, as long as the number will fit into your computer's memory, you'll be fine. "BigInteger.js is an arbitrary-length integer library for Javascript, allowing arithmetic operations on integers of unlimited size, notwithstanding memory and time limitations." – Stefan Steiger Feb 13 '19 at 19:15