Javascript - Number Number Conversions

Introduction

There are three functions to convert nonnumeric values into numbers:

  • the Number() casting function,
  • the parseInt() function, and
  • the parseFloat() function.

The first function, Number(), can be used on any data type; the other two functions are used specifically for converting strings to numbers.

Number() function performs conversions based on these rules:

Value
Boolean values
Number() returns
true and false get converted into 1 and 0, respectively.
numbers
the value is passed through and returned.
null
0
undefined
NaN
strings




If the string contains only numbers, optionally preceded by a plus or minus sign, it is converted to a decimal number, so "1" becomes 1, "123" becomes 123, and "011" becomes 11. leading zeros are ignored.
If the string contains a valid floating-point format, such as "1.1", it is converted into the appropriate floating-point numeric value. Leading zeros are ignored.
If the string contains a valid hexadecimal format, such as "0xf", it is converted into an integer that matches the hexadecimal value.
If the string contains no characters, empty, it is converted to 0.
If the string contains anything other than these previous formats, it is converted into NaN.
objects

valueOf() method is called and the returned value is converted based on the previously described rules.
If that conversion results in NaN, the toString() method is called and the rules for converting strings are applied.

Here are some concrete examples:

var num1 = Number("Hello world!");  //NaN 
var num2 = Number("");              //0 
var num3 = Number("000011");        //11 
var num4 = Number(true);            //1 

"Hello world" is converted into NaN because it has no corresponding numeric value.

empty string is converted into 0.

The string "000011" is converted to the number 11 because the initial zeros are ignored.

The value true is converted to 1.

The unary plus operator works the same as the Number() function.