parseInt bug

 here is a "bug" with the parseInt JavaScript function. The bug is not something that will affect you very often, but it is something you should be aware of. We've seen the bug in every browser except Opera.

We've created a button to demonstrate the bug. The bug is that parseInt can return an incorrect value. For example, parseInt("08") results in 0 instead of 8. And parseInt("09") results in 0 instead of 9. The reason for this is because the zero in front is trying to tell the browser that this is an octal (base 8) number, and "08" and "09" are not valid octal numbers. The button below builds statements from parseInt("01") through parseInt("09") and shows what the resulting value is. But it also does parseFloat("01") through parseFloat("09"). This shows that the bug does not exist with parseFloat.

Keep in mind that this bug only happens when the value being checked is a string and only when the string starts with a leading zero. So that's why it is difficult to notice. But if you're dealing with a web page that has user input, there's nothing prevening the user from entering 08 for a number field. To be 100% confident that you won't see the bug, use one of these two techniques:

parseInt(parseFloat(<my text value>))

parseInt(<my text value>, 10)

The "10" in the second example tells the browser that base-10 values should be used. Here is the button so you can see what's happening. The button puts up an alert box with the result of the "buildString" function, which is shown below:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值