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

如何在python中将浮点小数转换为定点小数,python,python-3.x,floating-point,decimal,precision,Python,Python 3.x,Floating Point,Decimal,Precision,我有一些库函数foo,它返回一个带两位小数的浮点值(表示价格)。我必须传递到另一个函数bar,它需要一个小数点,小数点后两位为固定点 value = foo() # say value is 50.15 decimal_value = decimal.Decimal(value) # Not expected. decimal_value contains Decimal('50.14999999999999857891452847979962825775146484375') bar(deci

我有一些库函数
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
问题: 如何将任意浮点转换为小数点后两位的固定小数点?并且不使用
str
进行中间字符串转换

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

更新:其他可能的解决办法 使用:

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

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

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

但是,为什么不干脆
str
?是否有令人信服的理由使用
Decimal.quantize
over
str
?@ChristianDean,因为
str
不能保证小数点后两位。啊,我明白了。我不知道。我喜欢
round
解决方案,因为它比
quantize
基本解决方案更容易读写。但请记住,它只在Python3上有效:在Python2上,
round
ing一个
Decimal
实例会返回一个
float
。谢谢!编辑以做笔记。
>>> from decimal import Decimal
>>> Decimal(50.15)
Decimal('50.14999999999999857891452847979962825775146484375')
>>> Decimal(50.15).quantize(Decimal('1.00'))
Decimal('50.15')
>>> decimal.Decimal(str(50.0))
Decimal('50.0')
>>> decimal.Decimal(50.0).quantize(decimal.Decimal('1.00'))
Decimal('50.00')