6

我正在尝试在“nan”浮点数上使用 string.format。

这是python 文档中对“g”选项的描述。

一般格式。这会将数字打印为定点数字,除非数字太大,在这种情况下它会切换到“e”指数表示法。Infinity 和 NaN 值分别格式化为 inf、-inf 和 nan。

这就是我在解释器(Python 2.6)中尝试的方法:

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

据我了解文档,输出应该是“nan”。

这是一个错误还是我做错了?

4

1 回答 1

8

repr(float)在 Python 2.6 和 Python 3.0 中已修复;见http://bugs.python.org/issue1635;但是str.format直到 2.7 分支才修复;见http://hg.python.org/cpython/rev/c5e0d9beebf9http://bugs.python.org/issue1580

我建议看看是否"{0!r}"适合你;这应该调用完整的repr代码。

如果您需要使用"{0:g}"格式规范,您可以尝试子类化float和覆盖__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'
于 2012-08-07T15:32:11.117 回答