Possible Duplicate:
Why parseInt() works like this?
I have an issue with parseInt() returning 0 unexpectedly, here's a sample:
parseInt('-06') = -6
parseInt('-07') = -7
parseInt('-08') = 0
Why is the result 0? Same if I keep going down (-09, -10, ect). The format of the string comes from my framework so I need to deal with it. Thanks!
You need to pass a radix parameter when you use parseInt
parseInt('-08', 10);
When you don't, and when the string you're parsing has a leading zero, parseInt produces different results depending on your browser. The most common issue is that the string will be treated as a base-8 number, which is what you're seeing.
That's why this worked for '-06' and '-07'—those are both valid base-8 numbers. Since '-08' isn't a valid base-8 number, the parse failed, and 0 was returned.
From MDN
radix
An integer that represents the radix of the above mentioned string. While this parameter is optional, always specify it to eliminate reader confusion and to guarantee predictable behavior. Different implementations produce different results when a radix is not specified.
Also note that you can use the unary + operator to convert these strings to numbers:
var str = '-08';
var num = +str;
console.log(num);
//logs -8
DEMO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With