In A Number or Its toFixed() Text?, you saw one total in two forms. The number kept working in calculations, while its toFixed() text joined onto whatever you added with +. That difference matters every time a script shows a result to a person.
Picture the last errand before your hike. You buy a fuel canister, a bag of trail mix, and a map, and you want your script to print the bill the way a shop receipt would. You’ll also want to show the steps you walked in a week, a number big enough to be hard to read without separators.
In this lesson, you’ll print numbers with a fixed number of decimal places, a dollar sign, and thousands separators. You’ll do every calculation with numbers and format only in the line that shows the result. You’ll also choose between rounding a number for further calculations and formatting it for display.
Show a Fixed Number of Decimal Places With toFixed()
A number doesn’t remember how you typed it. If you write 4.50, JavaScript stores the value four and a half, and it prints that value with as few digits as it needs. Start the Node REPL by typing node in the integrated terminal, and try it:
> const fuelPrice = 4.50
undefined
> fuelPrice
4.5
> fuelPrice.toFixed(2)
'4.50'
The trailing zero is gone from the number because 4.5 and 4.50 are the same value.
A price usually shows two decimal places, though, and that’s the job of toFixed(). Every number carries this tool, so you write it after the variable name and a dot. The number in its parentheses says how many decimal places you want, and the quotes in '4.50' show that the result is text.
When the number has more decimal places than you ask for, toFixed() rounds the number. When it has fewer, it adds zeros:
> const walkKm = 12.348
undefined
> walkKm.toFixed(1)
'12.3'
> const mapPrice = 12
undefined
> mapPrice.toFixed(2)
'12.00'
Round the Way Your Story Needs warned that the rounding recipe occasionally rounds a value ending in 5 down. toFixed() can do the same:
> const sample = 1.005
undefined
> sample.toFixed(2)
'1.00'
Like the Math tools from Round the Way Your Story Needs, toFixed() gives back a new value and leaves the variable alone. walkKm still holds 12.348, and mapPrice still holds 12.