Javascript - parseInt bug

Working in javascript on the my project, I found an interesting thing which I would like to share with you all.

parseInt() method in javascript is used to parse a string text into integer. For example to convert String “8” as integer 8 for processing, you will use it as follows:
var parsedValue = parseInt(“8”);

You can find more details about the parseInt() method on W3C Schools. http://www.w3schools.com/jsref/jsref_parseInt.asp

However, there is an interesting bug with parseInt(). When you try to parseInt("08") or parseInt("09"), it returns 0. This is because the leading zero tells the parseInt() method that it is an octal number and 08 is not a valid octal value. Hence the parsing returns 0 as output.

So, you might get this scenario when you trying to parse date values or month values containing leading zeros.

Workaround:
- Use the alternate form of parseInt(value, radix). This form forces the parsing of the string value as per your radix value. 10 indicate for decimal, 2 indicate for binary, 8 indicate. So, parseInt(“08”, 10) will force it to interpret the string value “08” as a decimal value and not an octal. Thus, this will return 8 correctly after parsing.
- First convert the value to a float and then parseInt(). For example: var parsedValue = parseInt(parseFloat(“08”)). This will give you 8 as result.

Comments

Popular posts from this blog

Personal Contact Manager

An apt quote

Alone