如何在python中将浮点数转换为定点十进制

bal*_*lki 2 python floating-point precision decimal python-3.x

我有一些库函数foo,它返回一个带有两位小数(代表价格)的浮点值。我必须传递给其他函数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
Run Code Online (Sandbox Code Playgroud)

题:

如何将任意浮点数转换为带有 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)
Run Code Online (Sandbox Code Playgroud)

Ant*_*ala 5

使用Decimal.quantize

在舍入并具有第二个操作数的指数后返回等于第一个操作数的值。

>>> from decimal import Decimal
>>> Decimal(50.15)
Decimal('50.14999999999999857891452847979962825775146484375')
>>> Decimal(50.15).quantize(Decimal('1.00'))
Decimal('50.15')
Run Code Online (Sandbox Code Playgroud)

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

>>> decimal.Decimal(str(50.0))
Decimal('50.0')
>>> decimal.Decimal(50.0).quantize(decimal.Decimal('1.00'))
Decimal('50.00')
Run Code Online (Sandbox Code Playgroud)