Pretty Printing - Decimal Places

Python will print real numbers to many decimal places, usually more than is necessary.
Run this code to see well over 10 decimal places


In [ ]:
answer = 4/7
print(answer)

Now, suppose you would like to have just two decimal places. We can use Python's format() function to help.
Run this code, it produces just two decimal places, rounding up as appropriate.


In [ ]:
answer = 4/7
answer_2dp = format(answer, '0.2f')
print(answer_2dp)

Next up, let's see how to print money! (without getting arrested):


In [ ]:
average_price = 300/11    #just some random calculation with lots of decimal places
average_price_2dp = format(average_price, '0.2f')
print("Average price £"+average_price_2dp)

Once you have run the code, your output should be:
Average price £27.27

Note:

  1. average_price_2dp is a string, not a number. It cannot be used in any further calculations.
  2. The format() function should only be used just before the formatted number is to be printed.
  3. The format() function can do a lot more. See https://docs.python.org/3/library/string.html#format-string-syntax for more info if you want.

You can now complete tasks 25 and 29