Skip to the content

Formatting

JavaScript · Unit 6: Strings

toFixed(n) leaves the number with that many decimals, rounding it.

That is what you want with money, so you do not see 33.333333333333336.

const total = 100 / 3;
console.log(total);
console.log(total.toFixed(2));

Prints

33.333333333333336
33.33

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    What does this code print?

  2. 2. Predict the output

    What does this code print?

  3. 3. Predict the output

    Watch out for the type of what toFixed returns. What does it print?

  4. 4. Complete the code

    Complete it to show the tip with two decimals.

  5. 5. Predict the output

    What does this code print?

  6. 6. Multiple choice

    What does "12345".padStart(3, "0") return?

  7. 7. Complete the code

    Complete the clock so 7 with 5 shows up as "07:05".

  8. 8. Find the bug

    This clock should print "07:05". Which line has the error?

  9. 9. Put the lines in order

    Order the function that builds a receipt line with the price lined up to the right.

  10. 10. Write the code

    Write withTax(price), which returns the price plus 8% sales tax, as a string with two decimals. For example, withTax(100) gives "108.00".

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →