HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Number Methods

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.


Formatting Numbers

These methods are used to convert numbers into strings with a specific format.

1. toFixed()

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"

2. toPrecision()

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"

3. toString()

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"

Converting Variables to Numbers

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.

Examples:

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
Note: 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.

Numeric Properties

JavaScript also provides properties that belong to the Number object. These represent limits of the language:

  • Number.MAX_VALUE — The largest possible number
  • Number.MIN_VALUE — The smallest possible number
  • Number.POSITIVE_INFINITY — Infinity
  • Number.NEGATIVE_INFINITY — -Infinity

Key Points to Remember

  • toFixed() is perfect for formatting money (decimals)
  • Number() is the strictest conversion method
  • parseInt() and parseFloat() can parse numbers out of strings
  • Primitive numbers automatically get access to these methods
  • Numeric methods return strings for formatted values