Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 685
einstein Avatar asked Dec 19 '10 04:12

einstein


People also ask

Does parseInt remove leading zeros?

The parseInt function parses a string argument and returns a number with the leading zeros removed.

What does parseInt () function do?

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 .

Why parseInt is not used more often in JavaScript?

parseInt() doesn't always correctly convert to integer In JavaScript, all numbers are floating point. Integers are floating point numbers without a fraction. Converting a number n to an integer means finding the integer that is “closest” to n (where “closest” is a matter of definition).

What can I use instead of parseInt?

parseFloat( ) parseFloat() is quite similar to parseInt() , with two main differences. First, unlike parseInt() , parseFloat() does not take a radix as an argument. This means that string must represent a floating-point number in decimal form (radix 10), not octal (radix 8) or hexadecimal (radix 6).

Does parseInt have a limit?

The range of int is between Integer. MAX_VALUE and Integer. MIN_VALUE inclusive (i.e. from 2147483647 down to -2147483648). You cannot parse the int value of out that range.


3 Answers

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

parseInt('01', 10);
like image 197
Sergey Akopov Avatar answered Sep 30 '22 07:09

Sergey Akopov


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

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

like image 28
Adam Vandenberg Avatar answered Sep 30 '22 09:09

Adam Vandenberg


Number prefixed with zero is parsed as octal.

like image 26
osgx Avatar answered Sep 30 '22 09:09

osgx