Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

Decimal Places

Division often gives a number with a lot of decimal places:

price = 10 / 3
print(price)

This prints:

3.3333333333333335

(The 5 at the end is a tiny inaccuracy: a computer stores most decimal numbers only approximately.)

That's no way to show a price. In an f-string, you can say how a number should look: after the value, write a colon and a format. The format .2f means two decimal places, and .1f one:

price = 10 / 3
print(f"Price: {price:.2f}")
print(f"{price:.1f}")
print(f"{2 / 3:.2f}")
print(f"{4.5:.2f}")
print(f"{5:.2f}")

This prints:

Price: 3.33
3.3
0.67
4.50
5.00

The f stands for a decimal number (in Python, a float), and the number after the dot says how many decimal places to show. The number is rounded: 2 / 3 is 0.666…, which shows as 0.67. When a number has fewer decimal places, zeros are added, so 4.5 shows as 4.50 and 5 as 5.00, the way prices are written.

The format changes only how the number is printed. The variable keeps its whole value, so you can go on calculating with it exactly:

average = 17 / 6
print(f"Average: {average:.1f}")
print(average)

This prints:

Average: 2.8
2.8333333333333335

A format with f works only for numbers. If the value is a text, for example a part you got from split(), the program ends with ValueError: Unknown format code 'f' for object of type 'str'. Turn the text into a number with float() first.

Instructions

  1. 1

    Print each price in the list prices with two decimal places and a dollar sign right in front of it, each on its own line: $4.50, $12.25 and $3.10. Keep the lines with the two lists: the exercise also tries other numbers in them.

  2. 2

    The list ratings holds the stars that customers gave the shop. Below, print their average with one decimal place: Rating: 4.2.

Back

11/12

  1. 1. Upper and Lower Case
  2. 2. Trimming Spaces
  3. 3. Replacing Text
  4. 4. Quiz: Text Methods
  5. 5. Searching in Text
  6. 6. Beginnings and Ends
  7. 7. Splitting Text
  8. 8. Joining a List
  9. 9. Slices
  10. 10. Quiz: Slices
  11. 11. Decimal Places
  12. 12. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.