Number methods allow you to work with numbers. Just like strings, primitive numbers can access methods because JavaScript converts them into temporary objects during execution. These methods are essential for formatting output and converting types.
These methods are used to convert numbers into strings with a specific format.
Returns a string representing a number with a specific number of decimals. This is the most common method for handling currency.
let x = 9.656;
console.log(x.toFixed(0)); // "10" (rounds)
console.log(x.toFixed(2)); // "9.66"
console.log(x.toFixed(4)); // "9.6560"
Returns a string with a number written with a specific total length.
let x = 9.656;
console.log(x.toPrecision()); // "9.656"
console.log(x.toPrecision(2)); // "9.7"
Returns a number as a string. Can also be used to convert numbers to different bases (like binary or hex).
let x = 123;
console.log(x.toString()); // "123"
console.log((123).toString()); // "123"
There are three global JavaScript methods that can be used to convert variables to numbers:
| Method | Description |
|---|---|
Number() |
Converts the entire variable to a number if possible. |
parseInt() |
Parses a string and returns a whole number (integer). |
parseFloat() |
Parses a string and returns a floating point number. |
console.log(Number("10")); // 10
console.log(Number("10.33")); // 10.33
console.log(parseInt("10.33")); // 10
console.log(parseFloat("10.33")); // 10.33
parseInt() and parseFloat() are more
flexible than Number() because they can pick out a number at the start of a
string: parseInt("10 years") returns 10.
JavaScript also provides properties that belong to the Number object. These
represent limits of the language:
Number.MAX_VALUE — The largest possible numberNumber.MIN_VALUE — The smallest possible numberNumber.POSITIVE_INFINITY — InfinityNumber.NEGATIVE_INFINITY — -InfinitytoFixed() is perfect for formatting money (decimals)Number() is the strictest conversion methodparseInt() and parseFloat() can parse numbers out of strings