JavaScript Number() function : The Number function is used to cast the other objects to the number. Number() is a global function in JavaScript.
Syntax of the Number() funciton :
Number(object)
object: It is required parameter. It could be string, integer, boolean or any object.
Number() function returns the numeric value of the passed parameter. If it is not able to convert it to number then it simply returns NaN.
Example of Number() function : Here I will show how to convert any variable to the number.
<!DOCTYPE html>
<html>
<body>
<p>To convert variables to number, click on button.</p>
<button onclick="myFunction()">convert</button>
<p id="container"></p>
<script>
function myFunction() {
var val1 = true;
var val2 = false;
var val3 = "99";
var val4 = "Hi";
var num =
Number(val1) + "<br>" +
Number(val2) + "<br>" +
Number(val3) + "<br>" +
Number(val4);
document.getElementById("container").innerHTML = num;
}
</script>
</body>
</html>
Output :
1
0
99
NaN
0 Comment(s)