如何在 python 中将浮点数转换为定点小数

How to convert float to fixed point decimal in python

我有一些库函数 foo,returns 一个带两位小数的浮点值(代表价格)。我必须传递给其他函数 bar ,它需要一个带有两位小数的定点小数。

value = foo() # say value is 50.15
decimal_value = decimal.Decimal(value) # Not expected. decimal_value contains Decimal('50.14999999999999857891452847979962825775146484375')
bar(decimal_value) # Will not work as expected

# One possible solution
value = foo() # say value is 50.15
decimal_value = decimal.Decimal(str(round(value,2))) # Now decimal_value contains Decimal('50.15') as expected
bar(decimal_value) # Will work as expected

问题:

如何将任意浮点数转换为2位小数的固定小数点?并且没有使用 str.

的中间字符串转换

我不担心性能。只是想确认中间 str 转换是否是 pythonic 方式。

更新:其他可能的解决方案

# From selected answer
v = 50.15
d = Decimal(v).quantize(Decimal('1.00'))

# Using round (Does not work in python2)
d = round(Decimal(v), 2)

使用Decimal.quantize:

Return a value equal to the first operand after rounding and having the exponent of the second operand.

>>> from decimal import Decimal
>>> Decimal(50.15)
Decimal('50.14999999999999857891452847979962825775146484375')
>>> Decimal(50.15).quantize(Decimal('1.00'))
Decimal('50.15')

与糟糕的 str 方法不同,这适用于任何数字:

>>> decimal.Decimal(str(50.0))
Decimal('50.0')
>>> decimal.Decimal(50.0).quantize(decimal.Decimal('1.00'))
Decimal('50.00')