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 inparseInt
>>>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'
parseIntfails 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
parseIntguesses 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
parseFloator to always specify your base.
Defaults that change on their own can't be trusted.
>>>parseInt('08',10)
8
相关文章推荐
- javaScript parseInt字符转化为数字函数使用小结
- javascript parseInt 大改造
- javascript parseInt()的问题
- JavaScript parseInt() 函数
- JavaScript parseInt() 函数 eval函数及计算器加运算
- javascript parseInt与Number函数的区别
- javascript parseInt() 函数的进制转换注意细节
- javascript parseInt 大改造
- 错误提示:The method parseInt(String) is undefined for the type Loginsample
- JavaScript parseInt() 函数
- JavaScript parseInt() toString()函数
- javaScript parseInt字符转化为数字函数使用小结
- JavaScript parseInt() 函数
- JavaScript parseInt() 函数
- JavaScript:理解parseInt
- [ExtJS5学习笔记]第二十七节 CMD打包错误 Error C2009: YUI Parse Error (identifier is a reserved word => debugger;)
- 原生javascript 表单同步提交和提交前操作 和 document.form.submit() is not a function
- 在c#中(int)、int.Parse()、int.TryParse、Convert.ToInt32()四种转换的区别
- [C#]Int32.TryParse()、int.Parse和Convert.ToInt32的区别
- 方法参数out(简单的实现int.Tyrparse()方法)