JavaScript Number() | Convert a Value to a Number

The JavaScript Number() method is used to convert a specified value to a number. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p>Number(40) = <span id="resOne"></span></p>
   <p>Number('40') = <span id="resTwo"></span></p>
   <p>Number("-40.345") = <span id="resThree"></span></p>

   <script>
      document.getElementById("resOne").innerHTML = Number(40);
      document.getElementById("resTwo").innerHTML = Number('40');
      document.getElementById("resThree").innerHTML = Number("-40.345");
   </script>
   
</body>
</html>
Output

Number(40) =

Number('40') =

Number("-40.345") =

JavaScript Number() Syntax

The syntax of Number() method in JavaScript is:

Number(x)

where x refers to a value that needs to be converted into a number.

The Number() method returns the same value x as a number. The NaN will be returned if the specified value x cannot be converted into its number counterpart. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p>Number("fresherearth") = <span id="res"></span></p>

   <script>
      document.getElementById("res").innerHTML = Number("fresherearth");
   </script>
   
</body>
</html>
Output

Number("fresherearth") =

Since the x parameter to Number() method is optional. Therefore providing nothing as parameter, will return 0. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p>Number() = <span id="res"></span></p>

   <script>
      document.getElementById("res").innerHTML = Number();
   </script>
   
</body>
</html>
Output

Number() =

The Number() method returns 0 and 1 if we provide boolean values (false and true) to it. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p>Number(false) = <span id="a"></span></p>
   <p>Number(true) = <span id="b"></span></p>

   <script>
      document.getElementById("a").innerHTML = Number(false);
      document.getElementById("b").innerHTML = Number(true);
   </script>
   
</body>
</html>
Output

Number(false) =

Number(true) =

Example of Converting a Value to a Number in JavaScript

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p>Type Before using Number() = <span id="abc"></span></p>
   <p>Type After using Number() = <span id="xyz"></span></p>

   <script>
      let val = "234";
      document.getElementById("abc").innerHTML = typeof(val);
      document.getElementById("xyz").innerHTML = typeof(Number("234"));
   </script>
   
</body>
</html>
Output

Type Before using Number() =

Type After using Number() =

Please note: The typeof() method returns the type of variable/value.

JavaScript Online Test


« Previous Tutorial Next Tutorial »