我希望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?。
当前回答
Use:
float_number = 12.234325335563
round(float_number, 2)
这将返回;
12.23
说明:
round函数接受两个参数;要舍入的数字和要返回的小数位数。这里我返回了两位小数。
其他回答
对于Python<3(例如2.6或2.7),有两种方法可以实现。
# Option one
older_method_string = "%.9f" % numvar
# Option two (note ':' before the '.9f')
newer_method_string = "{:.9f}".format(numvar)
但请注意,对于3以上的Python版本(例如3.2或3.3),首选选项二。
有关选项2的更多信息,我建议使用Python文档中的字符串格式链接。
关于选项一的更多信息,这个链接就足够了,并提供了各种标志的信息。
引用:将浮点数转换为特定精度,然后复制为字符串
对于原始Python:
对于浮点到字符串转换的2个小数点:
a = 13.949999999999999
format(a, '.2f')
对于浮点到浮点转换的2个小数点:
a = 13.949999999999999
round(float(a), 2)
or
float(format(a, '.2f'))
请尝试以下代码:
>>> a = 0.99334
>>> a = int((a * 100) + 0.5) / 100.0 # Adding 0.5 rounds it up
>>> print a
0.99
正如Matt所指出的,Python 3.6提供了f字符串,它们也可以使用嵌套参数:
value = 2.34558
precision = 2
width = 4
print(f'result: {value:{width}.{precision}f}')
显示结果:2.35
我看到的答案对浮点数(52.15)不起作用。经过一些测试,我使用的解决方案是:
import decimal
def value_to_decimal(value, decimal_places):
decimal.getcontext().rounding = decimal.ROUND_HALF_UP # define rounding method
return decimal.Decimal(str(float(value))).quantize(decimal.Decimal('1e-{}'.format(decimal_places)))
(将“value”转换为float和string非常重要,这样一来,“value”可以是float、decimal、integer或string类型!)
希望这对任何人都有帮助。