Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the radix for JavaScript's parseInt default to 8?

Tags:

Defaulting the radix to 8 (if the string starts with a 0) in JavaScript's parseInt function annoys me, only because I continue to forgot to pass the optional second argument as 10. I'm looking for an answer telling me why it makes sense to have it default to 8.

like image 884
Kirk Ouimet Avatar asked Apr 08 '11 20:04

Kirk Ouimet


People also ask

What is the default radix for parseInt?

By default radix is 10 (decimal).

What is the difference between number and parseInt?

Differences. Number() converts the type whereas parseInt parses the value of input. As you see, parseInt will parse up to the first non-digit character. On the other hand, Number will try to convert the entire string.

How does parseInt work?

The parseInt function converts its first argument to a string, parses that string, then returns an integer or NaN . If not NaN , the return value will be the integer that is the first argument taken as a number in the specified radix .


1 Answers

It only "defaults" to 8 if the input string starts with 0. This is an unfortunate carryover from C and C++.

You can use Number('0123') instead, or, as you said in the question, parseInt('0123', 10).

How do I work around JavaScript's parseInt octal behavior?


Can you tell me more about this carryover?

  • Javascript eval function returning Octal value
  • Octal number literals: When? Why? Ever?

Note: ECMAScript strict mode removes octal syntax.

like image 181
Matt Ball Avatar answered Oct 03 '22 04:10

Matt Ball