0

I'm trying to convert a string to number in Javascript, but here is my problem :

var string = "068999999501111443";
parseInt(string); // 68999999501111440
Number(string); // 68999999501111440

Why does this happen and how to fix it ?

Thanks

9
  • 3
    Because the number is larger than Number.MAX_SAFE_INTEGER. Commented Oct 2, 2015 at 9:13
  • @limelights - no, it isn't that. If it was, then the output would be a lot more different to the input. Commented Oct 2, 2015 at 9:13
  • 2
    You are over the integer max length of +/- 9007199254740991, so javascript will have problems handling this number stackoverflow.com/questions/307179/… Commented Oct 2, 2015 at 9:14
  • Welcome to the wonderful world of finite precision numerical representations. Every such scheme will have numbers that it cannot represent exactly, just as decimal numbers with a finite number of digits cannot exactly represent one third. If you try to represent a number that cannot be represented exactly, it will be represented approximately. If you don't want this, don't use finite precision representations. For example, why not keep the number in a string? Commented Oct 2, 2015 at 9:28
  • @fuyushimoya : is there a way to handle large numbers in JS ? (i really need to use large numbers in my calculations) Commented Oct 2, 2015 at 9:31

1 Answer 1

1

This is because the number is too large to be stored accurately. It is being stored as a floating point number, which can only store a certain amount of precision. Beyond it's maximum precision, you'll get what look like weird rounding errors.

You'll get similar effects for decimals with a large number of decimal places. This is more well known, as it tends to occur more often, but it's exactly the same effect that is happening here.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.