1

I am parsing a string to an integer and it works fine until certain values. After that the result is not exact. The code will be like below

parseInt(someString);//this string will have any value.

For example when i execute the below code i get result as 18446744073709552000

parseInt(18446744073709551616) //result 18446744073709552000

But I am expecting the result to be 18446744073709551616.

Can any one tell what is wrong? And how do I accomplish what I want.

I need to check if a string exceeds the maximum value or not. So how is that possible?

ckv
  • 10,539
  • 20
  • 100
  • 144
  • Check here: http://stackoverflow.com/questions/307179/what-is-javascripts-max-int-whats-the-highest-integer-value-a-number-can-go-t – Fred Thomsen Feb 05 '14 at 04:41
  • These questions do not answer my question of How I can check if a string exceeds the maximum integer value in javascript. That is the answer i am looking for. I have edited the question also accordingly. – ckv Feb 05 '14 at 04:44
  • If you need to do this you'll need to use a js library designed for large numbers like http://jsfromhell.com/classes/bignumber – dave Feb 05 '14 at 04:44
  • @ckv: You didn't mention strings originally. The value you pass to `parseInt` is a number (because you are using a number literal). You might want to update your example. – Felix Kling Feb 05 '14 at 04:45
  • @FelixKling: Updated the code and question. – ckv Feb 05 '14 at 04:52

1 Answers1

3

You're exceeding the max value of Integer in JavaScript, subsequently losing precision.

What is JavaScript's highest integer value that a Number can go to without losing precision?


For the reason why you're getting zeroes:

Let mathInt be the mathematical integer value that is represented by Z in radix-R notation, using the letters A-Z and a-z for digits with values 10 through 35. (However, if R is 10 and Z contains more than 20 significant digits, every significant digit after the 20th may be replaced by a 0 digit, at the option of the implementation; and if R is not 2, 4, 8, 10, 16, or 32, then mathInt may be an implementation-dependent approximation to the mathematical integer value that is represented by Z in radix-R notation.)

http://ecma262-5.com/ELS5_HTML.htm#Section_15.1.2.2

Community
  • 1
  • 1
Alex
  • 34,899
  • 5
  • 77
  • 90
  • Is'nt there anyway to make a this check whether it has exceeded the max value. – ckv Feb 05 '14 at 04:40
  • 3
    but shouldn't it throw an error instead of returning another value which is again bigger than the max value? – techfoobar Feb 05 '14 at 04:40
  • the javascript number type can exceed the maximum integer by converting to a double essentially. javascript uses the number type not integer or double or float. it is really it's own encapsulation and can vary between browsers. – Daniel Williams Feb 05 '14 at 04:48