Friday, February 12, 2010

Javascript - ParseInt Bug

There 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

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 (base8) number, and "08" and "09" are not valid octal numbers.

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())

parseInt(, 10)

courtesy :
http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256C85006A6604
http://www.go4expert.com/forums/showthread.php?t=857