conversion from float to Decimal in python-2.6: how to do it and why they didn't do it

后端 未结 3 1361
栀梦
栀梦 2021-02-07 12:35

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 t

3条回答
  •  梦毁少年i
    2021-02-07 12:43

    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

提交回复
热议问题