How to convert a value to a number in JavaScript?

JavascriptObject Oriented ProgrammingFront End Technology

Javascript has introduced Number() method to convert a value into a number. This method can convert number strings to numbers and boolean values to 1's or 0's. Let's discuss it briefly.

syntax

var num = Number(value);

Example-1

In the following example, Number() method has converted number strings and boolean values to numbers and displayed the output as shown. 

Live Demo

<html>
<body>
<script>
   document.write(Number("10.5") + "</br>");
   document.write(Number(" 123 ") + "</br>");
   document.write(Number(true) + "</br>");
   document.write(Number(false) + "</br>");
   document.write(Number(null));
</script>
</body>
</html>

Output

10.5
123
1
0
0

Example-2

This method not only converts a normal value to a number but also converts a hexadecimal value to a number as shown below.

 Live Demo

<html>
<body>
<script>
   document.write(Number(" ") + "<br>");  
   document.write(Number("") + "<br>");  
   document.write(Number("123e-1") + "<br>");  
   document.write(Number("0xFF") + "<br>");
</script>
</body>
</html>

Output

0
0
12.3
255
raja
Published on 01-Aug-2019 08:07:56
Advertisements