JS parseInt


parseInt() function converts a numeric string into number data type, if the string is not a number, return NaN.

var x="5";
var y=parseInt(x); //5


When webpage receives number from the user input, the data type usually is string. Sometimes parseInt() is important to help getting the correct results, e.g. when add a numeric string and a number.

var x="5";
var y=x+5;
alert(y); //55
var y=parseInt(x)+5;
alert(y); //55
var y=x * 1 + 5;
alert(y); //55


If the string starts with "0x", it will be looked as in hexadecimal format, and start with "0" as in octal format.

var x="0x35";
var y=parseInt(x);
alert(y); //53
var y=parseInt("09");
alert(y); //9


The format of the numeric string can also be specified, 8 as octal, 16 as hexadecimal and 10 as decimal.

var y=parseInt("12",16); //18
alert(y); //18
var y=parseInt("12",8); //10
alert(y); //10
var y=parseInt("12",10); //12
alert(y); //12




endmemo.com © 2024  | Terms of Use | Privacy | Home