Use Number() cast function to convert values to a number
Description
Number() can be used on any data type. And it performs conversions based on these rules:
Parameter | Number Function Returns |
---|---|
Boolean true | 1 |
Boolean false | 0 |
null | 0 |
undefined | NaN |
Empty string("") | 0 |
String with only number, for example "123" | 123 |
String with only number and plus sign, for example "+123" | 123 |
String with only number and minus sign, for example "-123" | -123 |
Leading zeros are ignored, for example "0123" | 123 |
Leading zeros are ignored, for example "+0123" | 123 |
Leading zeros are ignored, for example "-0123" | -123 |
String with valid floating-point format, such as "1.1" | 1.1 |
String with valid floating-point format, such as "+1.1" | 1.1 |
String with valid floating-point format, such as "-1.1" | -1.1 |
Leading zeros are ignored, such as "01.1" | 1.1 |
String with hexadecimal format, "0xf" | 15 |
String with hexadecimal format, "-0xf" | -15 |
String with not a number value, for example "asdf" | NaN |
objects | the valueOf() method is called and the returned value is converted |
Example
var num1 = Number("Hello world!"); //NaN
console.log(num1);//from ww w. ja va 2 s .co m
var num2 = Number(""); //0
console.log(num2);
var num3 = Number("000011"); //11
console.log(num3);
var num4 = Number(true); //1
console.log(num4);
console.log(Number("-123"));
console.log(Number("+123")); //123
console.log(Number("-0123")); //-123
console.log(Number("0xf")); //15
console.log(Number("-0xf")); //-15
console.log(Number("asdf")); // NaN
The code above generates the following result.
Note
The unary plus operator works the same as the Number() function.