Number Methods
Format and parse numbers with built-in methods.
Syntax
num.toFixed(2)
parseInt('42px')Numbers have methods for formatting and conversion:
toFixed(n)— format withndecimal places (returns a string).parseInt()/parseFloat()— read a number out of a string.Number.isInteger()— check for a whole number.
Example
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.
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.
const userInput = "42px";
console.log(parseInt(userInput, 10)); // 42
console.log(parseFloat("3.14em")); // 3.14
console.log(parseInt("0xFF", 16)); // 255toPrecision and toString base
Converts a number to binary and hexadecimal strings with toString, and limits significant digits with toPrecision.
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