如何限制多个数字输出中的小数位数?

时间:2019-09-13 21:48:56

标签: python-3.x

我最近开始学习Python,并编写了一个简单的程序来计算圆的面积,但是,我不喜欢答案的输出,而是想知道如何限制多个变量在输出中保留小数位。

示例代码:

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")

我得到的输出:

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

我想要的输出:

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

非常感谢!

1 个答案:

答案 0 :(得分:2)

使用f弦

您的最后一行应该是:

x

使用新的f字符串从您的代码输出:

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