JavaScript parseInt() bug

Very recently I have faced a strange problem with JavaScript parseInt() function. It returns incorrect result when try to parse value like "08","09"...... But it works for "01" to "07".
So I have tried to find solution in community. Then find that this was a JavaScript bug.

Problem:

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. We've seen the bug in every browser except Opera.

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.

Solution:

parseInt(parseFloat(09))
Or,
parseInt(09, 10)
The "10" in the second example tells the browser that base-10 values should be used.

Hope that it will helpful for other developers.Thanks.

Comments

Popular posts from this blog

The model backing the 'MyDBContext' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the DropCreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data.

How can I get a value of a property from an anonymous type (C#)

Check/Uncheck all items in a CheckBoxList using Javascript