Numbers: Formatting Numbers

Join the AI Workshop to learn more about AI and how it can be applied to web development. Next cohort February 1st, 2026

The AI-first Web Development BOOTCAMP cohort starts February 24th, 2026. 10 weeks of intensive training and hands-on projects.


JavaScript provides several methods for formatting numbers as strings.

toFixed()

You can use this method to get a string representing the number in fixed point notation:

new Number(21.2).toFixed() //21

You can add an optional number setting the digits as a parameter:

new Number(21.2).toFixed(0) //21
new Number(21.2).toFixed(1) //21.2
new Number(21.2).toFixed(2) //21.20

toExponential()

You can use this method to get a string representing the number in exponential notation:

new Number(10).toExponential() //1e+1 (= 1 * 10^1)
new Number(21.2).toExponential() //2.12e+1 (= 2.12 * 10^1)

You can pass an argument to specify the fractional part digits:

new Number(21.2).toExponential(1) //2.1e+1
new Number(21.2).toExponential(5) //2.12000e+1

Notice how we lost precision in the first example.

toPrecision()

This method returns a string representing the number to a specified precision:

new Number(21.2).toPrecision(0) //error! argument must be > 0
new Number(21.2).toPrecision(1) //2e+1 (= 2 * 10^1 = 2)
new Number(21.2).toPrecision(2) //21
new Number(21.2).toPrecision(3) //21.2
new Number(21.2).toPrecision(4) //21.20
new Number(21.2).toPrecision(5) //21.200

toLocaleString()

Formats a number according to a locale.

By default the locale is US english:

new Number(21.2).toLocaleString() //21.2

We can pass the locale as the first parameter:

new Number(21.2).toLocaleString('it') //21,2

This is eastern arabic:

new Number(21.2).toLocaleString('ar-EG') //٢١٫٢

There are a number of options you can add. See the MDN page to learn more.

toString()

This method returns a string representation of the Number object. It accepts an optional argument to set the radix:

new Number(10).toString() //10
new Number(10).toString(2) //1010
new Number(10).toString(8) //12
new Number(10).toString(16) //a

Adding Leading Zeros

To add a leading zero when the number is less than 10:

Math.floor(mynumber)
    .toString()
    .padStart(2, '0')

The padStart() method pads the string to the specified length with the given character.

For example, to format video length where 5:4 should be 5:04:

const seconds = 4
const formatted = seconds.toString().padStart(2, '0') //'04'

Lessons in this unit:

0: Introduction
1: Number Basics
2: Number Validation
3: Parsing Numbers
4: ▶︎ Formatting Numbers
5: Number Recipes
6: The Binary Number System
7: Underscores in numbers
8: The Decimal Number System
9: Converting Numbers from Decimal to Binary