您的位置:首页 > Web前端 > JavaScript

javascript parseInt is broken

2010-01-28 18:00 274 查看

javascript parseInt is broken

I was debugging some strange errors in a date conversion function I was writing, and I stumbled upon something that amazed me... a strange bug in
parseInt


>>>parseInt('06')
6
>>>parseInt('07')
7
>>>parseInt('08')
0
>>>parseInt('09')
0
>>>parseFloat('08')
8
>>>parseFloat('09')
9
 
 

 

Clearly for the strings
'08'
and
'09'
parseInt
fails to return the right value. One workaround is easy, use
parseFloat
.

Why does this happen and where should I report this? I find it extremely odd that it happens in both Firefox and Internet Explorer 6 & 7; there must be some explanation right?

You can test it out for yourself using the FireBug javascript console), or by using one of these two links

alert(parseInt('07')+' == 7 ?')
alert(parseInt('08')+' == 8 ?')

Ok, Ok, so now that I explained how you would expect it to work (and clearly how I expected it to work) I'm going to answer my own question (yes I hate it when I do that too)

The problem is with how
parseInt
guesses the base of your number. Read the parseInt spec. Instead of always defaulting to base 10, it tries to guess, and if the first character is '0' it thinks you want to parse as an octal number, and if it starts with '0x' it thinks you want hexadecimal.

So, the solution is either to use
parseFloat
or to always specify your base.

Defaults that change on their own can't be trusted.

>>>parseInt('08',10)
8
 
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息