Number Methods

Format and parse numbers with built-in methods.

Syntaxnum.toFixed(2) parseInt('42px')

Numbers have methods for formatting and conversion:

  • toFixed(n) — format with n decimal places (returns a string).
  • parseInt() / parseFloat() — read a number out of a string.
  • Number.isInteger() — check for a whole number.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Format a currency value to exactly two decimal places with toFixed before displaying it in an invoice.
  • Convert a large number to exponential notation for a scientific data display widget.
  • Parse a numeric string from a query parameter with parseInt before using it as an array index.

More examples

toFixed for currency display

Uses toFixed() to round a number to a specified number of decimal places, returning a string.

Example · js
const amount = 1234.5678;
console.log(amount.toFixed(2)); // "1234.57"
console.log(amount.toFixed(0)); // "1235"

parseInt and parseFloat

Uses parseInt to extract a leading integer from a CSS value string, with a base-10 radix.

Example · js
const userInput = "42px";
console.log(parseInt(userInput, 10)); // 42
console.log(parseFloat("3.14em"));   // 3.14
console.log(parseInt("0xFF", 16));   // 255

toPrecision and toString base

Converts a number to binary and hexadecimal strings with toString, and limits significant digits with toPrecision.

Example · js
const n = 255;
console.log(n.toString(2));   // "11111111" – binary
console.log(n.toString(16));  // "ff" – hex
console.log((1234.5).toPrecision(4)); // "1235"

Discussion

  • Be the first to comment on this lesson.
Number Methods — JavaScript | SoundsCode