我有一个库函数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
问题:
如何将任意浮点数转换为带有两位小数的固定小数点? 而且不使用中间字符串转换,也不必担心性能。只是要确认中间字符串转换是否符合Python风格。
更新:其他可能的解决方案
# 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)