Python float to Decimal conversion

后端 未结 9 1959
渐次进展
渐次进展 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:41

    Python <2.7

    "%.15g" % f
    

    Or in Python 3.0:

    format(f, ".15g")
    

    Python 2.7+, 3.2+

    Just pass the float to Decimal constructor directly, like this:

    from decimal import Decimal
    Decimal(f)
    

提交回复
热议问题