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

  • 3
    Because the number is larger than `Number.MAX_SAFE_INTEGER`. – fuyushimoya Oct 02 '15 at 09:13
  • @limelights - no, it isn't that. If it was, then the output would be a lot more different to the input. – Simba Oct 02 '15 at 09:13
  • 2
    You are over the integer max length of +/- 9007199254740991, so javascript will have problems handling this number http://stackoverflow.com/questions/307179/what-is-javascripts-highest-integer-value-that-a-number-can-go-to-without-losin – baao Oct 02 '15 at 09: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? – David Schwartz Oct 02 '15 at 09:28
  • @fuyushimoya : is there a way to handle large numbers in JS ? (i really need to use large numbers in my calculations) – donpachi Oct 02 '15 at 09:31
  • Try google `big number api javascript`, should be some libs exist like [big.js](https://github.com/MikeMcl/big.js/), [bignumber.js](https://github.com/MikeMcl/bignumber.js/), or you can implement one. There should be plenty of resource to implement that. – fuyushimoya Oct 02 '15 at 09:34
  • @David Schwartz : i can't use string, i need numbers because i have to modulo this number... – donpachi Oct 02 '15 at 09:35
  • @donpachi You can modulo a string. Do it the same way you would do it on paper. Surely you learned long division in school. – David Schwartz Oct 02 '15 at 09:51
  • @David Schwartz : you're a genious ! i use your method and it works like a charm :) Thank you !! – donpachi Oct 02 '15 at 13:36

1 Answers1

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.

Simba
  • 4,952
  • 3
  • 19
  • 29