简体   繁体   中英

Formatting a nan float in python

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?

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM