JavaScript ยท Chapter 20 of 55

JavaScript Number Methods

Numbers have useful methods for formatting and conversion, such as `toFixed()` for decimal places, `toString()` for converting to text, and global functions like `parseInt()` and `parseFloat()`.

The `Number` object also provides static helpers like `Number.isInteger()` and `Number.parseFloat()` for safer type checking.

Formatting numbers

`toFixed(2)` rounds a number to two decimal places and returns it as a string, useful for displaying currency.

Parsing strings to numbers

`parseInt('42px')` returns 42, stopping at the first non-numeric character. `parseFloat('3.14 meters')` returns 3.14.

Example 1 (javascript)
let price = 9.4567;
console.log(price.toFixed(2));
Output
9.46

toFixed rounds and formats as a string with fixed decimals.

Example 2 (javascript)
console.log(parseInt("42px"));
console.log(parseFloat("3.14 meters"));
Output
42
3.14

Both parsing functions extract the leading numeric portion.

Key points

  • `toFixed(n)` formats a number with n decimal places as a string.
  • `parseInt()` and `parseFloat()` extract numbers from strings.
  • `Number.isInteger()` checks for whole numbers.
  • `Number()` converts a value to a number, or returns NaN if impossible.
๐Ÿ’ก Note: toFixed() returns a string, so convert it back with Number() if further math is needed.

๐Ÿ“ Quick Quiz

1. What does `(9.4567).toFixed(2)` return?

2. What does `parseInt('42px')` return?

3. toFixed() returns a value of type: