I have to convert some input data to integer.
I found parseInt()
function.
Everything is good if the input is string:
console.log(parseInt("123")) //123
Even if the string starts with 0:
console.log(parseInt("0123")) //123
But if a number starts with 0, it will give 83!
console.log(parseInt(0123)) //83 instead of 123
I heard about that's because octal behavior (Javascript parseInt() with leading zeros), so I gave a radix parameter to it:
console.log(parseInt(0123,10)) //83!!!
Still 83!!!
And then, the strangest of all:
I thinked: octal 123 must give 123 in octal!
But it gave NaN
:
console.log(parseInt(0123, 8)) //NaN
Why this strange behavior?! And how can I fix it?
Thanks!!!
In this code, you can defined a number (rather than a string) in octal format, then passed it to parseInt
. Then parseInt
casts that number to a string ("83"
), and parses it again.
If you pass a string to parseInt
you will get the expected result:
console.log(parseInt('0123'))