In this post, I am sharing how to convert string to number in JavaScript.

Conversion with parseInt and parseFloat

The parseInt function parses a string argument and returns an integer of a specified base (radix)

If the base (radix) argument is not specified, it is taken out of the context i.e. string argument:

  • base is 16 (hexadecimal) if the input starts with 0x or 0X
  • base is 8 (octal) or 10 (decimal) if the input starts with 0 (zero). Note that this behaviour is implementation-dependent and may not be consistent across all browsers. For that reason it is recommended to always specify base (radix).
  • base is 10 (decimal) if the input begins with any other value.
console.info(parseInt("0xFF"))   // value 255 - base 16

console.info(parseInt("10"))     // value 10  - base 10
console.info(parseInt("10", 16)) // value 16 - base 16
console.info(parseInt("10", 2))  // value 2  - base 2

console.info(parseInt("08"))     // value 8 - base 10
console.info(parseInt("08", 10)) // value 8 - base 10
console.info(parseInt("08", 8))  // value 0! Why? 
                                 // digit 8 is invalid in base 8

console.info(parseInt("011"))    // value 11 - base 10
console.info(parseInt("011", 8)) // value 9 - base 8

The parseFloat function parses a sting argument and returns a floating point number. Note that unlike parseInt, parseFloat does not take second argument base / radix.

console.info(parseFloat("234.332")); // 234.332
console.info(parseFloat("92")); // 92

Following parsing returns 0 as this is the only recognised character

console.info(parseFloat("0xFF")); // 0

The statement below returns NaN (Not a Number) as none of the characters (FF) is recognised by the parserFloat function

console.info(parseFloat("FF")); // NaN

Conversion with Unary Plus

Unary plus converts a string into number if the string is already in the form of an integer e.g.

var x1 = +"10";
console.info(x1, typeof x1); // 10 'number'

var x2 = 1 + +"10";
console.info(x2, typeof x2); // 11 'number'

var x3 = 1 + "10";           // no unary plus
console.info(x3, typeof x3); // 110 'string'

Conversion with Math.floor and other Math functions

If you provide a string, which is already in the form of an integer or float, as an argument of Math.floor then the floor method automatically converts string to a number e.g.

var x = Math.floor("10");
console.info(x, typeof x);    // 10 'number'

var y = Math.floor("10.10");
console.info(y, typeof y);    // 10 'number'

You can also see automated string to number conversion using other Math methods such as Math.ceil, Math.abs, or Math.round.

x = Math.round("233");
console.info(x, typeof x);    // 233 'number'

x = Math.ceil("233");
console.info(x, typeof x);    // 233 'number'

x = Math.abs("233");
console.info(x, typeof x);    // 233 'number'

NOTE that the value of Math.floor(x) is the same as the value of -Math.ceil(-x).