Converting a Python Float to a String without losing precision

后端 未结 5 918
被撕碎了的回忆
被撕碎了的回忆 2021-02-01 03:40

I am maintaining a Python script that uses xlrd to retrieve values from Excel spreadsheets, and then do various things with them. Some of the cells in the spreadshe

5条回答
  •  名媛妹妹
    2021-02-01 04:11

    As has already been said, a float isn't precise at all - so preserving precision can be somewhat misleading.

    Here's a way to get every last bit of information out of a float object:

    >>> from decimal import Decimal
    >>> str(Decimal.from_float(0.1))
    '0.1000000000000000055511151231257827021181583404541015625'
    

    Another way would be like so.

    >>> 0.1.hex()
    '0x1.999999999999ap-4'
    

    Both strings represent the exact contents of the float. Allmost anything else interprets the float as python thinks it was probably intended (which most of the time is correct).

提交回复
热议问题