1

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

FZs
  • 16,581
  • 13
  • 41
  • 50

2 Answers2

2

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'))
Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
1

You should use a combination of a string and a radix to get the correct value. Here's an example:

parseInt(01234) // returns 668
parseInt('01234', 10) // returns 1234
Garrett Kadillak
  • 1,026
  • 9
  • 18