1

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?

Vandervidi
  • 642
  • 2
  • 14
  • 32
  • 3
    `Number.MAX_SAFE_INTEGER` is the max value that you can represent with javascript without "loosing precision". this number is over that limit. see [this post](http://stackoverflow.com/questions/307179/what-is-javascripts-highest-integer-value-that-a-number-can-go-to-without-losin) – Hacketo Nov 12 '15 at 10:43
  • 2
    From the code above it looks as though you are passing an int and not the original string? – OliverRadini Nov 12 '15 at 10:43
  • @OliverRadini yes. fixed this . – Vandervidi Nov 12 '15 at 10:45
  • @Hacketo Is there a way to overcome this? – Vandervidi Nov 12 '15 at 10:46
  • 1
    @VanderVidi if you don't do math on this number, keep it as string, else could use some biginteger library I guess. – Hacketo Nov 12 '15 at 10:47
  • http://stackoverflow.com/questions/5353388/javascript-parsing-int64 – sayingu Nov 12 '15 at 11:00

3 Answers3

3

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

Community
  • 1
  • 1
OliverRadini
  • 6,238
  • 1
  • 21
  • 46
2

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.

1

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>
Alex
  • 21,273
  • 10
  • 61
  • 73