如何将浮点数舍入到一定数量的小数位 Python

How to round float to certain amount of decimal places Python

我有一个从随机库中随机生成的浮点数,我想根据其他数字将它缩短到任意数量的地方。

示例:

输入 = 4.06098152

处理数字,四舍五入到千位

输出 = 4.061

我该怎么做?

您可以使用内置的 round 函数: 括号中的第二个参数给出了四舍五入的位数

x=input("Enter a decimal number: ")
print(round(float(x),3))