String to number conversion in JavaScript


In this post, I am sharing several different ways of converting a 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:

  • the base is 16 (hexadecimal) if the input starts with 0x or 0X
  • the base is 8 (octal) or 10 (decimal) if the input starts with 0 (zero). Note that this behavior is implementation-dependent and may not be consistent across all browsers. For that reason, it is always recommended to specify base (radix).
  • the 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 string 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 recognized character.

console.info(parseFloat('0xFF')) // 0

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

console.info(parseFloat('FF')) // NaN

Conversion with Unary Plus

Unary plus converts a string into a 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 a 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).


Tags:

#conversion#javascript#number#string


You may also be interested in: