Convert string to int in javascript

So you want to convert a javascript string to an int (integer)? Here’s the quick solution because this is always the kind of stuff I have to look-up online…

The function you are looking for is parseInt. Here’s how you use it.

var my_string;
var my_int;

my_string = "10";

// Convert my_string to an integer
// This is the only important line for this solution
my_int = parseInt(my_string);

// my_int is now equal to 10 and of type number (js integer)
document.write("my_int is equal to: " + my_int);
document.write("<br />");
document.write("my_int is of type: " + (typeof my_int));

And there you have it… if you run this you get the following output:

my_int is equal to: 10
my_int is of type: number

You can see that when you ask what type the variable is, it returns “number”.  That’s because javascript only has one kind of number.  It does not differentiate between “int”, “float”, “double”, “decimal” and the other types of data types that some other programming languages might differentiate between.

Hopefully that helps some of you.  Enjoy.

Leave a Comment