0

I've recently started learning Python and have made a simple program to calculate the area of a circle, however, I don't like the output of the answer and wanted to know how it would be possible to limit the number of decimal places in the output for multiple variables.

Example code:

import numpy as np
rad = input("Insert the radius of your circle: ")
radius = float(rad)
area = np.pi*(radius**2)
per=2*np.pi*radius

print("The area and perimeter of your chosen circle of radius "+str(radius)+" are: "+str(area)+" and "+str(per)+" respectively")

Output I get:

Insert the radius of your circle: 56.3

The area and perimeter of your chosen circle of radius 56.3 are: 9957.87481815703 and 353.7433327942107 respectively

Output I would like:

Insert the radius of your circle: 56.3

The area and perimeter of your chosen circle of radius 56.3 are: 9957.87 and 353.74 respectively

Many thanks!

Yago Tobio
  • 39
  • 1
  • 7
  • Check out https://docs.python.org/3/library/string.html#formatspec – benvc Sep 13 '19 at 22:06
  • 2
    Possible duplicate of [Limiting floats to two decimal points](https://stackoverflow.com/questions/455612/limiting-floats-to-two-decimal-points) – wjandrea Sep 13 '19 at 22:16

1 Answers1

3

Use f-strings

Your last line should be:

print(f'The area and perimeter of your chosen circle of radius {radius:.03f} are: {area:.03f} and {per:.03f} respectively')

Output from you code with new f-string:

Insert the radius of your circle:  6
The area and perimeter of your chosen circle of radius 6.000 are: 113.097 and 37.699 respectively
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158