python - 如何舍入 float ?

标签 python python-3.x floating-point numbers

我有一个可变的浮点变量(例如:2.003)

而且我想自动将其更改为仅保留 2 位小数。

最佳答案

您可以使用 round功能:

print round(2.003, 2)   # 2.0
print round(2.013, 2)   # 2.01

否则保持精度,只显示你想要的小数位数:

print '%.2f' % 2.003    # 2.00
print '%.2f' % 2.013    # 2.01

关于python - 如何舍入 float ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25182685/

相关文章:

python - Buildbot 不以默认配​​置启动

python - 在 For 循环中格式化 Django ValidationError

c - 下溢如何导致上溢?

Python map 对象不可下标

python - 使用正则表达式解析特殊符号 '( )'

floating-point - 散列浮点向量的好方法?

compression - 压缩 float 据

python - 此构造函数不带参数 lcd

python - 为什么 numpy.polyfit 大幅偏离?

Python 简单 Salesforce 选择所有字段