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

谁都会走 提交于 2020-08-26 21:32:41

问题


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???


回答1:


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);


来源:https://stackoverflow.com/questions/16880327/why-am-i-getting-weird-result-using-parseint-in-node-js-different-result-from

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!