The JavaScript parseInt global function returns the integer value of a variable. It parses the string representation of that variable and returns an integer using the specified base.
var int_val = parseInt(value [, base]);
Examples:
parseInt("11"); // returns 11
parseInt("11", 2); // returns 3
parseInt("11", 8); // returns 9
parseInt("11", 16); // returns 17If the variable cannot be converted to a string, the parseInt() function returns NaN. However it is possible to convert compound types such as arrays and objects to numbers, provided that their toString methods return numeric strings:
function Foo(arg) {
this.x = arg;
}
Foo.prototype.toString = function() {
return this.x;
}
var f = new Foo(42);
parseInt(f); // returns 42The base argument must be an integer between 2 and 36, otherwise parseInt() returns NaN. If base is undefined, null or 0, JavaScript assumes the following:
The parseInt function walks through the characters of the string until it finds a character that is not a numeral in the specified base. The value parsed up to that point is then converted to an integer. Consequently, the result of the parseInt() function depends on the leftmost characters of the string.
If the first character of the string cannot be converted to a number, parseInt returns NaN.
The base defines which characters are used to represent numbers. As pointed out earlier, the base determines when the parseInt() function should stop parsing.
For example, the decimal system uses the digits from 0 through 9. On the other hand, the hexatridecimal system (base 36) uses the digits from 0 through 9 plus the letters A through Z. As a result, a radix of 10 will cause the parseInt() function to stop when it encounters a letter. On the contrary, when using base 36, parseInt will not stop until it encounters a non alphanumeric value.
The following examples illustrate this:
parseInt("12a"); // base 10 (implied), returns 12
parseInt("12a", 10); // base 10, returns 12
parseInt("12a", 36); // base 36, returns 1378
parseInt("12a?", 36); // base 36, returns 1378The isNaN() function can be used to determine if the result of the parseInt() function is NaN.
Using the parseInt() function together with the Number.toString() method we can create a small function to convert a number from one base to another:
function base_convert(number, from_base, to_base) {
return parseInt(number, from_base || 10).toString(to_base || 10);
}Both from_base and to_base have to be integers between 2 and 36.
Base conversion examples:
base_convert(222, 8, 36); // 42 base_convert(10101, 2, 10); // 21 base_convert(0xfc); // 252
If you see a typo, want to make a suggestion or have anything in particular you'd like to know more about, please drop us an e-mail at hello at diveintojavascript dot com.
Copyright © 2010-2011 Dive Into JavaScript