Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parseInt("08") returns 0 [duplicate]

Possible Duplicate:
Workarounds for JavaScript parseInt octal bug

I've been working on a javascript function, setting date objects by declaring the year, month & date. However, when the month has a value of 08 or 09, 0 is returned when using parseInt(). See below:

parseInt("01") //returns 1
parseInt("02") //returns 2
parseInt("03") //returns 3
parseInt("04") //returns 4
parseInt("05") //returns 5
parseInt("06") //returns 6
parseInt("07") //returns 7
parseInt("08") //returns 0?
parseInt("09") //returns 0?
parseInt("10") //returns 10

I've created a jsFiddle to demonstrate this issue:

http://jsfiddle.net/GhkEf/

Why does parseInt("08") and parseInt("09") return 0?

like image 697
Curtis Avatar asked Sep 07 '12 13:09

Curtis


People also ask

What does parseInt return?

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 .

What does parseInt return for empty string?

If parseInt() is given an empty string or a null value it will also return NaN, rather than converting them to 0. This gives us a mechanism by which we can test values using a combination of parseInt() and isNaN().

Can parseInt return undefined?

Try replacing your return with return decimalnum; -- you may still be returning undefined. parseInt is not for rounding - it actually takes the integer component of a number, or coerces a string to be a number. If you want to round, use Math. round .

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).


2 Answers

That's because numbers started with 0 are considered to be octal. And 08 is a wrong number in octal.

Use parseInt('09', 10); instead.

like image 79
zerkms Avatar answered Oct 18 '22 05:10

zerkms


It's being parsed as an octal number. Use the radix parameter in parseInt.

parseInt('08', 10);

An update: As of ES5, browsers should not have this bug. Octal literals require to be in the form 0o12 to be considered Octal numbers. 08 by default is now considered a decimal number in ES5, however, all browsers may not support this yet, so you should continue to pass the radix parameter to parseInt

like image 30
Some Guy Avatar answered Oct 18 '22 05:10

Some Guy