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

后端 未结 3 1355
栀梦
栀梦 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条回答
  • 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

    0 讨论(0)
  • 2021-02-07 12:46

    According to 2.7's What's New documentation (emphasis added)

    Conversions between floating-point numbers and strings are now correctly rounded on most platforms. These conversions occur in many different places: str() on floats and complex numbers; the float and complex constructors; numeric formatting; serializing and deserializing floats and complex numbers using the marshal, pickle and json modules; parsing of float and imaginary literals in Python code; and Decimal-to-float conversion.

    So, although they could have done that prior to 2.7, they apparently didn't feel comfortable doing that with the rounding problems that existed.

    0 讨论(0)
  • 2021-02-07 12:48

    Probably because the behavior of a direct conversion can be counterintuitive if you don't know a few implementation details about floats. As stated in the docs:

    Note Decimal.from_float(0.1) is not the same as Decimal('0.1'). Since 0.1 is not exactly representable in binary floating point, the value is stored as the nearest representable value which is 0x1.999999999999ap-4. That equivalent value in decimal is 0.1000000000000000055511151231257827021181583404541015625.

    If you convert to a string, you can control the precision you want to use, so you can get an accurate conversion to Decimal.

    The new method was introduced in Python 2.7 - that's why it isn't in 2.6. New features are not backported to older versions.

    0 讨论(0)
提交回复
热议问题