The Number()
function converts the object argument
to a number that represents the object's value.
If the value cannot be converted to a legal number, NaN is returned.
var firstVal = "5";
var secondVal = "5";
var result = Number(firstVal) + Number(secondVal);
console.log("Result: " + result);
/* ww w . j av a 2 s. c o m*/
var num = Number("+1.1")
console.log(num);
num = Number("-1.1")
console.log(num);
num = Number("+123")
console.log(num);
num = Number("asdf")
console.log(num);
num = Number("0123")
console.log(num);
num = Number("0xf")
console.log(num);
num = Number("-0xf")
console.log(num);
num = Number("01.1")
console.log(num);
num = Number(null)
console.log(num);
num = Number(false)
console.log(num);
num = Number("")
console.log(num);
num = Number(undefined)
console.log(num);
The code above generates the following result.
Number |
Yes | Yes | Yes | Yes | Yes |
Number(object)
Parameter | Description |
---|---|
object | Optional. A JavaScript object. If no argument is provided, it returns 0. |
It return a number by converting object to numbers. If the value cannot be converted to a legal number, NaN is returned. If no argument is provided, it returns 0.
The following code shows how to convert different object values to their numbers.
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">test</button>
<p id="demo"></p>
<script>
function myFunction() {<!--from www .j ava2 s.c o m-->
var x1 = true;
var x2 = false;
var x3 = new Date();
var x4 = "9 9";
var x5 = "999 888";
var n =
Number(x1) + "<br>" +
Number(x2) + "<br>" +
Number(x3) + "<br>" +
Number(x4) + "<br>" +
Number(x5);
document.getElementById("demo").innerHTML = n;
}
</script>
</body>
</html>
The code above is rendered as follows: