Python float to Decimal conversion

后端 未结 9 1987
渐次进展
渐次进展 2020-12-05 03:50

Python Decimal doesn\'t support being constructed from float; it expects that you have to convert float to a string first.

This is very inconvenient since standard

9条回答
  •  孤街浪徒
    2020-12-05 04:34

    Python does support Decimal creation from a float. You just cast it as a string first. But the precision loss doesn't occur with string conversion. The float you are converting doesn't have that kind of precision in the first place. (Otherwise you wouldn't need Decimal)

    I think the confusion here is that we can create float literals in decimal format, but as soon as the interpreter consumes that literal the inner representation becomes a floating point number.

提交回复
热议问题