JavaScript String to Int

Very often when you are coding JavaScript, you find that you need to convert a string value to an int value. This can happen for instance when you let the user type a number into a field but then have to use that input for mathematical operations and therefore need to make sure you’re dealing with an actual integer.

There is a very easy way to achieve such JavaScript string to int conversion, and this is the parseInt function:

parseInt(string, radix);

This function will take a string and optionally the base of the number and do a string to int conversion, outputting an integer value.

There are however a few caveats with this JavaScript string to int operation, which you need to be aware of. Namely, string beginning with “0″ or “0x” will be interpreted as octal or hexadecimal, respectively. Thus it’s always a good idea to specify the second argument to be 10, if you really want to make sure the string to int conversion is done in decimal.

You can read more about the JavaScript parseInt function in an earlier post.

Tags: , , ,

Comments are closed.