Ad space (banner)
🟨JavaScript Lessons
Lesson 50 / 69

Formatting Numbers (Digit Alignment and Decimal Precision)

In this lesson you'll learn how to format numbers so you can produce clean, well-aligned output for things like price displays or sequentially numbered filenames. This is for people searching "JavaScript toFixed usage" or "JavaScript digit alignment zero-padding."

.toFixed(digits) aligns the number of decimal places, and .padStart(length, "0") pads the front of a number with zeros to align its digit count. These are handy for displaying prices, or building sequentially numbered filenames. Also note that .toFixed() returns a string, not a number.

The sample code converts the number 1234.5 into the string "1234.50", aligned to 2 decimal places, using .toFixed(2), and converts the number 7 to a string and then into a 3-digit, sequential-looking string, "007", using .padStart(3, "0"). Also remember that padStart is a string-only method, so it can't be applied directly to a number.

A common beginner stumbling block is that, because the result of .toFixed() is a string, trying to use it directly in a further calculation causes errors or bugs. A value formatted for display is strictly "a string meant to be shown" — you need to use the original number for any further calculations.

Displaying a raw calculation result usually produces inconsistent, hard-to-read digit counts, so it's common in real work to insert this kind of formatting right before something is shown on screen. It's a small step for tidying up appearance, but it's an important part of the process that has a big impact on the quality of the user experience.

JavaScript
OUTPUT

💡 Anything passed to console.log() appears in the output below.

Ad space (banner)
Ad space (in-article)