I have the following string:
var x = "10207122232230383";
When parsing it to integer i get the same number + 1.
var y = parseInt(x, 10);
console.log(y);
This prints 10207122232230384. Why is this happening?
I have the following string:
var x = "10207122232230383";
When parsing it to integer i get the same number + 1.
var y = parseInt(x, 10);
console.log(y);
This prints 10207122232230384. Why is this happening?
The number is too large for js to parse as an integer. This is explained well in this post:
What is JavaScript's highest integer value that a Number can go to without losing precision?
From a practical point of view, you can handle large numbers in javascript using a library, for instance https://github.com/MikeMcl/bignumber.js/
There are other libraries available which will help you to achieve the same thing, they are discussed at length here: https://github.com/MikeMcl/big.js/issues/45
In Javascript any integer which until unless cross Number.MAX_SAFE_INTEGER
that will be precision free.When it crosses this MAX_SAFE_INTEGER then it starts representing the doubleprecision 64-bit format IEEE 754 values as specified in the IEEE Standard for Binary Floating-Point Arithmetic.
To Over Come this You can go with any one of this libraries BigNum or Biginteger.
That number is too large to be represented as an integer. You will have to use a BigNumber
library as Javascript does not have a long
type. You could, for example, use the the BigInt
library developed by Michael M, below I have given an example how to use it.
document.write('Maximum value integer in JavaScript: ' + Number.MAX_SAFE_INTEGER + '<br>')
x = new BigNumber("10207122232230383")
document.write('Your value divided by 1: ' + x.div(1) + '<br>')
document.write('Your value divided by 3: ' + x.div(3) + '<br>')
<script src="https://cdnjs.cloudflare.com/ajax/libs/bignumber.js/2.1.0/bignumber.js"></script>