![]() |
JavaScript parseInt() bug
On 2nd June, 2006
|
Recent Articles
Similar Articles
I'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: Code: JavaScript
Code: JavaScript
|
|
|
#2 |
|
Newbie Member
Join Date: Aug 2007
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
Rep Power: 0 ![]() |
Re: JavaScript parseInt() bug
there are other techniques, try these: Code:
parseInt(<my text value>.replace(/^0+/g, ''));
ex.: parseInt("08".replace(/^0+/g, ''));
parseInt(<my text value> * 1);
ex.: parseInt("08" * 1);
|
|
|
|
|
|
#3 |
|
Team Leader
![]() |
Re: JavaScript parseInt() bug
Good, but the techniques mentioned above are technically correct.
__________________
Vote for the Most Entertaining Member of 2008 To err is human,to detect is divine! |
|
|
|
![]() |
|
| Currently Active Users Reading This Article: 1 (0 members and 1 guests) | |
| Article Tools | Search this Article |
| Display Modes | |
| Bookmarks | |
|
|
|
|||||||||||||||||||||||||||||||||||||