JavaScript function parseInt() doesn't parse numbers with leading 0 correctly
Asked Answered
G

4

6

I have some zeros prior to a positive integer. I want to remove the zeros so only the positive integer remains. Like '001' will only be '1'. I thought the easiest way was to use parseInt('001'). But what I discovered is that it don't works for the number 8 and 9. Example parseInt('008') will result in '0' instead of '8'.

Here are the whole html code:

<html> <body>
<script>
var integer = parseInt('002');
document.write(integer);

</script>
</body> </html>

But can I somehow report this problem? Do anyone know an another easy workaround this problem?

Gaud answered 19/12, 2010 at 4:4 Comment(1)
also, stripping leading zeros by using parseInt('008').toString() is very clumsy, consider using RegExp insteadOtiliaotina
Y
10

This is documented behavior: http://www.w3schools.com/jsref/jsref_parseInt.asp

Strings with a leading '0' are parsed as if they were octal.

Yablon answered 19/12, 2010 at 4:6 Comment(2)
MDN docs are generally of much higher quality than their w3schools counterparts. Here's the relevant MDN page.Nth
FireFox 21 has curiously decided to remove this functionality. Chrome has apparently been that way for a while: stackoverflow.com/questions/14542377Uppermost
P
15

You have to specify the base of the number (radix)

parseInt('01', 10);
Pirandello answered 19/12, 2010 at 4:7 Comment(1)
Yep, and a JS code quality tool like JSLint (jslint.com) can give you a heads up about it :)Zygapophysis
Y
10

This is documented behavior: http://www.w3schools.com/jsref/jsref_parseInt.asp

Strings with a leading '0' are parsed as if they were octal.

Yablon answered 19/12, 2010 at 4:6 Comment(2)
MDN docs are generally of much higher quality than their w3schools counterparts. Here's the relevant MDN page.Nth
FireFox 21 has curiously decided to remove this functionality. Chrome has apparently been that way for a while: stackoverflow.com/questions/14542377Uppermost
D
3

Number prefixed with zero is parsed as octal.

Draggletailed answered 19/12, 2010 at 4:6 Comment(1)
That's not the whole story -- it's browser and version dependent.Nth
C
1

This is not actually a bug. For legacy reasons strings starting with 0 are interpreted in octal, and in octal there is no digit 8. To work around this you should explicitly pass a radix (i.e. parseInt("008", 10)).

Chemash answered 19/12, 2010 at 4:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.