繁体   English   中英

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

[英]How to convert float to fixed point decimal in python

我有一些库函数foo ,它返回带有两个小数位的浮点值(表示价格)。 我必须传递到其他功能bar ,该功能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方式。

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

# 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

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

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

与bad str方法不同,它适用于任何数量:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM