我希望a四舍五入到13.95。我试过用圆形,但我得到:
>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999
有关标准库Decimal类的类似问题,请参阅How can I format a Decimal to always show 2 Decimal places?。
我希望a四舍五入到13.95。我试过用圆形,但我得到:
>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999
有关标准库Decimal类的类似问题,请参阅How can I format a Decimal to always show 2 Decimal places?。
当前回答
orig_float = 232569 / 16000.0
14.5355625
short_float = float("{:.2f}".format(orig_float))
14.54
其他回答
内置round()在Python 2.7或更高版本中运行良好。
例子:
>>> round(14.22222223, 2)
14.22
查看文档。
下面是使用format函数的简单解决方案。
float(format(num, '.2f'))
注意:我们将数字转换为浮点数,因为format方法返回字符串。
我使用的方法是字符串切片。它相对快速和简单。
首先,将浮点数转换为字符串,然后选择您希望的长度。
float = str(float)[:5]
在上面的单行中,我们将值转换为字符串,然后将字符串仅保留为其前四位数字或字符(包括)。
希望这有帮助!
如果您想处理金钱,请使用Python十进制模块:
from decimal import Decimal, ROUND_HALF_UP
# 'amount' can be integer, string, tuple, float, or another Decimal object
def to_money(amount) -> Decimal:
money = Decimal(amount).quantize(Decimal('.00'), rounding=ROUND_HALF_UP)
return money
这很简单,比如:
使用十进制模块进行快速正确舍入的十进制浮点运算:d=十进制(10000000.0000009)为了实现舍入:d.quantite(十进制('0.01'))将产生十进制('10000000.00')使上述干燥:def round_decimal(数字,指数='0.01'):decimal_value=十进制(数字)return decimal_value.g量化(十进制(指数))或定义round_decimal(数字,小数位数=2):decimal_value=十进制(数字)return decimal_value.g量化(十进制(10)**-decimal_places)
PS:对其他人的批评:格式不是舍入。