Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does parseInt() return an unexpected result when I pass a string with a leading zero?

Tags:

javascript

parseInt('1') = 1
parseInt('01') = 1
parseInt('5') = 5
parseInt('05') = 5
parseInt('8') = 8

But why:
parseInt('08') = 0
parseInt('09') = 0

like image 488
Sergey Metlov Avatar asked Dec 09 '11 11:12

Sergey Metlov


3 Answers

Always use the overload that takes the radix as the second parameter:

parseInt('011',10) = 11
like image 122
Jonas Høgh Avatar answered Nov 01 '22 02:11

Jonas Høgh


here is a hint:

parseInt('011') = 9

If it's starting with 0 it's parsed as an octal number.

like image 9
Karoly Horvath Avatar answered Nov 01 '22 02:11

Karoly Horvath


Numbers start with 0(not 0x) are octal numbers. Therefore 8 and 9 are not a valid octal numbers.

like image 8
Prince John Wesley Avatar answered Nov 01 '22 03:11

Prince John Wesley