Number()
Converts a value to a number.
Available since: ES1
Syntax
Number(value)Parameters
| Parameter | Type | Description |
|---|---|---|
| value | any | The value to convert to a number. |
Return value
numberA number, or NaN if the conversion fails.
Examples
A string into a number:
console.log(Number('42') + 1);Output:
43How different values are converted:
console.log(Number('3.5'), Number(' 7 '), Number(''));
console.log(Number('12px'), Number(true), Number(null));Output:
3.5 7 0
NaN 1 0Notes
Number() requires the whole string to be a number (spaces around it are fine), otherwise it returns NaN. To read a number from the start of a string like 12px, use parseInt() or parseFloat(). The unary plus +value does the same as Number(value).
See also
- parseInt — Converts a string to an integer.
- parseFloat — Reads a floating-point number from the start of a string.
- String() — Converts any value to a string.
- Boolean() — Converts a value to true or false.
Related recipes
In the tutorial
- Type conversion — How to turn a string into a number and back in JavaScript — Number, String, Boolean, parseInt and implicit conversion.