Converting a Python Float to a String without losing precision

后端 未结 5 891
被撕碎了的回忆
被撕碎了的回忆 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条回答
  •  Happy的楠姐
    2021-02-01 04:31

    EDIT: I am wrong. I shall leave this answer here so the rest of the thread makes sense, but it's not true. Please see John Machin's answer above. Thanks guys =).

    If the above answers work that's great -- it will save you a lot of nasty hacking. However, at least on my system, they won't. You can check this with e.g.

    import sys
    print( "%.30f" % sys.float_info.epsilon )
    

    That number is the smallest float that your system can distinguish from zero. Anything smaller than that may be randomly added or subtracted from any float when you perform an operation. This means that, at least on my Python setup, the precision is lost inside the guts of xlrd, and there seems to be nothing you can do without modifying it. Which is odd; I'd have expected this case to have occurred before, but apparently not!

    It may be possible to modify your local xlrd installation to change the float cast. Open up site-packages\xlrd\sheet.py and go down to line 1099:

    ...
    elif rc == XL_INTEGER:
                        rowx, colx, cell_attr, d = local_unpack('

    Notice the float cast -- you could try changing that to a decimal.Decimal and see what happens.

提交回复
热议问题