Skip to content

JavaScript Number() method | Converts a value to a number

  • by

Use JavaScript Number() method to convert a string or other value to the Number type. If the value cannot be converted, NaN is returned.

Number(value)

Note: it will return values based on input.

  • booleans, Number() returns 0 or 1.
  • dates, Number() returns milliseconds since January 1, 1970 00:00:00.
  • strings, Number() returns a number or NaN.

The value parameter represents the value that you want to convert to a number. It can be a string, a boolean, a numeric value, or an object with a valueOf() or toString() method.

JavaScript Number() method

Simple example code converts various data types to numbers.

<!DOCTYPE html>
<html>
<body>

  <script>
    console.log(Number(true))
    console.log(Number(false))
    console.log(Number(new Date()))

    console.log(Number("999"))

    const a1 = 5e9;
    console.log(a1);

    const a = 4 - 'hello';
    console.log(a);

    const n = '23';
    const result1 = Number(n);
    console.log(result1);

  </script>

</body>
</html> 

Output:

JavaScript Number method

Number Objects

You can also create numbers using the new keyword. For example,

const a = 45;

// creating a number object
const b = new Number(45);

console.log(a); // 45
console.log(b); // 45

console.log(typeof a); // "number"
console.log(typeof b); // "object"

When using the Number() method to parse strings, it will ignore leading and trailing white spaces. However, if the string contains any non-numeric characters (except for spaces), it will result in NaN.

Do comment if you have any doubts or suggestions on this JS Basic method topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading