python decimal 转换为float_python-2.6中从float到decimal的转换:怎么做,为什么他们不这样做...

Direct conversion from float to Decimal was implemented in python-2.7, both in Decimal's constructor and with the Decimal.from_float() classmethod.

Python-2.6 instead throws a TypeError suggesting to convert to string first:

TypeError: Cannot convert float to Decimal. First convert the float to a string

so my usual workaround is this:

if sys.version_info < (2, 7):

Decimal.from_float = classmethod(lambda cls, x: cls(str(x)))

That's just a literary translation from the error message - and I just don't bother implementing it in the constructor too.

If it's that simple, why didn't they implement it in the first place instead of telling the user to do it in a TypeError? Is that the best method available (and by extension is that the one used in python-2.7 and newer?)

解决方案

Your workaround is not the RightWayToDoIt(tm) because it loses information. The lossless way to convert is shown in the recipe for float_to_decimal() shown in the Decimal FAQ.

The reason we didn't include Decimal.from_float in Python 2.6 is because we were being conservative about introducing unintentional interactions between binary floats and decimal floats. By Python 2.7, this was all worked out and you can just write Decimal(f) where f is a binary float.

Other than the small nuisance in 2.6, I hope you're enjoying the Decimal module

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值