Why am I getting weird result using parseInt in node.js? (different result from chrome js console)
Asked Answered
S

1

14

I just noticed that:

//IN CHROME JS CONSOLE
parseInt("03010123"); //prints: 3010123

//IN NODE.JS
parseInt("03010123"); //prints: 790611

Since both are based on V8, why same operation yielding different results???

Sperling answered 2/6, 2013 at 6:20 Comment(7)
code.google.com/p/v8/issues/detail?id=1645Vaca
What version of Node? I can't reproduce it.Toadstool
@RenatoGama: Works fine in 0.10.4.Toadstool
This is why parseInt() should always be used with a radix. (I can reproduce it with 0.8.18.)Beckybecloud
@Juhana what is radix?Sperling
developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Beckybecloud
@Juhana your link actually answers my question, thanks!Sperling
E
28

Undefined behavior occurs when the string being passed to parseInt has a leading 0, and you leave off the radix parameter.

An integer that represents the radix of the above mentioned string. Always specify this parameter to eliminate reader confusion and to guarantee predictable behavior. Different implementations produce different results when a radix is not specified.

Some browsers default to base 8, and some to base 10. I'm not sure what the docs say about Node, but clearly it's assuming base 8, since 3010123 in base 8 is 790611 in base 10.

You'll want to use:

parseInt("03010123", 10);
Effectually answered 2/6, 2013 at 6:38 Comment(3)
thats it! thanks. you may want to improve your answer by adding this link as reference: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Sperling
you can also use Number() as alternative.Cwm
Node 6.6: parseInt("03010123"); -> 3010123Grind

© 2022 - 2024 — McMap. All rights reserved.