Javascript is great. But some over intelligency cause also great problem to the developer.

Here I give some string to integer conversion result in JavaScript,

1.  parseInt("01")=>1

2.  parseInt("05")=>5

3.  parseInt("08")=>0

4.  parseInt("09")=>0

 

Here javascript is giving wrong result for 3 and 4.

Problem:

When javascript get Zero leading string as parseInt parameter, it takes 8 base system for conversion automatically instead of 10 base.

Solution:

Simply set the base explicitly like below,

3. parseInt("08",10)=>8

4. parseInt("09",10)=>9

It is best practice in javascript to set the conversion "base" during any type number parsing.

 

Comments

habib's picture

Yes it is correct. Javascript parseInt function failed to convert to number for "08" and "09"

Added another 2 solutions for save typecasting

1. Number("08") => 08

   Number("09") => 09

Number function did same thing as parseInt without any bug.

2. parseFloat("08") => 08

If you only work with Integer value then

you can use like parseInt(Number("08")) or parseInt(parseFloat("08") for just keep integer value.

Remember that Javascript has only Number datatype for handle numeric values.

Number datatype can store both integer and float value as well.

 

habib's picture

Already we know that Javascript parseInt default conversion base is very. It depends on provided input value. If value is 0x then it will be hexa(16), only 0 then octal(8) otherwise decimal(10). But actually we work with decimal number system which base is 10. So we need to write a following method and reference that method from my master/base page though all page/ js file can use it.

var parseInteger = window.parseInt;

window.parseInt = function(x){
  return parseInteger(x, 10);
}
 
parseInt("08")); => 8
 
1st Line> take reference actuall window objects parseInt method and store it to parseInteger local variable.
2nd line>override default parseInt method(actually it is a member of browser window object). Inside that method i just call my referenced parseInteger method (which is actually original parseInt method) and call it with 10 as base parameter.
 
3rd line> then we see how to call it same as parseInt("08") or we can window.parseInt("08"). As if we call. Then it will fix all my praseInt. 
 
This is a tricky solution. I hope it will help for backward compatablitity if you think that in many places of your application either current or old use parseInt method and can face same "08" or "09" issue then can use this trick.
It is better solution for backward compatability for others.
 
Thanks Ashik  vi for correct me that parseInt number system is vary based on input value. Reference Url
another interesting things from Ashik vi is
 
unary + operator will work same like Number function.
 
parseInt(+("08")) =  parseInt(Number("08")) = 8
 

Add new comment