我希望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?。
当前回答
如果您想处理金钱,请使用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
其他回答
你遇到了一个关于浮点数的老问题,不是所有的数字都能精确表示。命令行只是显示内存中的完整浮点形式。
对于浮点表示法,舍入版本是相同的数字。由于计算机是二进制的,它们将浮点数存储为整数,然后将其除以2的幂,因此13.95将以类似于125650429603636838/(2**53)的方式表示。
双精度数字的精度为53位(16位),常规浮点数的精度为24位(8位)。Python中的浮点类型使用双精度来存储值。
例如
>>> 125650429603636838/(2**53)
13.949999999999999
>>> 234042163/(2**24)
13.949999988079071
>>> a = 13.946
>>> print(a)
13.946
>>> print("%.2f" % a)
13.95
>>> round(a,2)
13.949999999999999
>>> print("%.2f" % round(a, 2))
13.95
>>> print("{:.2f}".format(a))
13.95
>>> print("{:.2f}".format(round(a, 2)))
13.95
>>> print("{:.15f}".format(round(a, 2)))
13.949999999999999
如果您只在小数点后两位(例如显示货币值),那么您有两个更好的选择:
使用整数并以美分而非美元存储值,然后除以100转换为美元。或者使用小数等固定点数。
我看到的答案对浮点数(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类型!)
希望这对任何人都有帮助。
Use:
float_number = 12.234325335563
round(float_number, 2)
这将返回;
12.23
说明:
round函数接受两个参数;要舍入的数字和要返回的小数位数。这里我返回了两位小数。
要计算,我使用函数截断值也许对你有帮助
import math
def truncate(number, digits) -> float:
stepper = pow(10.0, digits)
return math.trunc(stepper * number) / stepper
print(truncate((0.1 + 0.2), 2))
为了修复Python和JavaScript等类型动态语言中的浮点,我使用了这种技术
# For example:
a = 70000
b = 0.14
c = a * b
print c # Prints 980.0000000002
# Try to fix
c = int(c * 10000)/100000
print c # Prints 980
您还可以按以下方式使用Decimal:
from decimal import *
getcontext().prec = 6
Decimal(1) / Decimal(7)
# Results in 6 precision -> Decimal('0.142857')
getcontext().prec = 28
Decimal(1) / Decimal(7)
# Results in 28 precision -> Decimal('0.1428571428571428571428571429')