There are three functions to convert nonnumeric values into numbers:
Number()
function, parseInt()
functionparseFloat()
function. The Number()
can be used on any data type.
The other two functions are used for converting strings to numbers.
Each of these functions reacts differently to the same input.
The Number()
function performs conversions based on the following rules:
Data | Convert to |
---|---|
Boolean values | true and false get converted into 1 and 0, respectively. |
numbers | the value is simply passed through and returned. |
null | Number() returns 0. |
undefined | Number() returns NaN. |
strings | If the string contains only numeric characters, optionally preceded by a plus or minus sign, it is always converted to a decimal number. Number("1") becomes 1, Number("123") becomes 123 Number("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 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 is empty, it is converted to 0. If the string contains anything other than these previous formats, it is converted into NaN . |
object | When applied to objects, the valueOf() method is called and the returned value is converted based on the rules above. If that conversion results in NaN , the toString() method is called and the rules for converting strings are applied. |
Here are some examples:
let num1 = Number("Hello world!"); // NaN let num2 = Number(""); // 0 let num3 = Number("000011"); // 11 let num4 = Number(true); // 1
The string "Hello world" is converted into NaN
because it has no corresponding numeric value.
The 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.