Formatting a nan float in python

泪湿孤枕 提交于 2019-12-07 05:02:25

问题


I'm trying to use string.format on a 'nan' float.

Here's the description of the 'g' option from the python documentation.

General format. This prints the number as a fixed-point number, unless the number is too large, in which case it switches to 'e' exponent notation. Infinity and NaN values are formatted as inf, -inf and nan, respectively.

And here's what i get trying it in the interpreter (Python 2.6):

>>> print "{0:g}".format(float('nan'))
-1.#IND

As I understand the documentation, the output should be "nan".

Is this a bug or am I doing it wrong?


回答1:


repr(float) was fixed in Python 2.6 and Python 3.0; see http://bugs.python.org/issue1635; however str.format was not fixed until the 2.7 branch; see http://hg.python.org/cpython/rev/c5e0d9beebf9 and http://bugs.python.org/issue1580.

I'd recommend seeing if "{0!r}" works for you; that should call into the non-broken repr code.

If you need to use "{0:g}" format spec, you could try subclassing float and overriding __format__:

class FixFloat(float):
    def __format__(self, format_spec):
        return 'nan' if math.isnan(self) else float.__format__(self, format_spec)

"{0:g}".format(FixFloat(1.2345e9))
'1.2345e+09'
"{0:g}".format(FixFloat(float('nan')))
'nan'


来源:https://stackoverflow.com/questions/11849158/formatting-a-nan-float-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!