Sunday, 9 December 2018

JavaScript: Convert a string to an integer

‘parseInt’ method converts the string into an integer.

Syntax
parseInt(string, radix);

First argument represents a string, if the argument is not a string, then it is converted to string by calling the toString method on it.

Radix specifies the numerical system to be used. It can have the value between 2 to 36.

HelloWorld.js
console.log("Number in decimal : " + parseInt("16", 10));
console.log("Number in binary : " + parseInt("10000", 2));
console.log("Number in octal : " + parseInt("020", 8));
console.log("Number in hexa : " + parseInt("0x10", 16));

Output
Number in decimal : 16
Number in binary : 16
Number in octal : 16
Number in hexa : 16


‘parseInt’ method only returns integers, not the decimals.

console.log(parseInt("16.234", 10)); // Prints 16

If parseInt methods encounters any character that is not a numeral in the given radix, then it ignores that character and all succeeding characters and returns the integer value parsed up to that point. If the first character can’t be converted to a number, then parseInt returns NaN.

console.log(parseInt("1A", 16)); //26
console.log(parseInt("1AX", 16)); // 26
console.log(parseInt("1XA", 16)); // 1
console.log(parseInt("X1A", 16)); // NaN



Previous                                                 Next                                                 Home

No comments:

Post a Comment