Monday, December 9, 2013

Javascript - parseInt

parseInt("12345"): 12345

// In IE 8, it outputs 5349
parseInt("012345"): 12345

parseInt("0x12345"): 74565

parseInt("12345",8): 5349

var numString = "012345";
// remove leading zeros in case of old browser using octal radix
numString = numString.replace(/^0*/,"");
parseInt(numString): 12345


If using latest version of browser can see parseInt("012345") giving number 12345 as output.
However, in some old browser, e.g. IE 8 , if the string parameter starts with a "0", it uses octal radix(8) to convert the string.
In IE 8, parseInt("012345") gives number 5349 as output, where it uses 8 as radix instead.



In order to support the browser compatibility for most of the browsers, developer can either strip off the leading zeros or give provide the radix parameter.
Simple regular expression can used to replace the leading zeros.
Or, one can use parseInt("012345",10) to ensure a decimal radix (10).
Just like this article does, check out the source of this page.

No comments:

Post a Comment