5

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?

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
einstein
  • 13,389
  • 27
  • 80
  • 110

4 Answers4

15

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

parseInt('01', 10);
Sergey Akopov
  • 1,130
  • 1
  • 11
  • 25
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.

Adam Vandenberg
  • 19,991
  • 9
  • 54
  • 56
  • 2
    MDN docs are generally of much higher quality than their w3schools counterparts. [Here's](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseInt) the relevant MDN page. – Matt Fenwick Dec 14 '12 at 19:19
  • [FireFox 21](https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Releases/21) has curiously decided to [remove this functionality](https://bugzilla.mozilla.org/show_bug.cgi?id=786135). Chrome has apparently been that way for a while: http://stackoverflow.com/questions/14542377 – Patrick M May 15 '13 at 00:15
3

Number prefixed with zero is parsed as octal.

osgx
  • 90,338
  • 53
  • 357
  • 513
  • 2
    That's not the [whole story](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseInt) -- it's browser and version dependent. – Matt Fenwick Dec 14 '12 at 19:20
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)).

Paul Wheeler
  • 18,988
  • 3
  • 28
  • 41