如何以非科学记数法获得大量数字?

时间:2015-01-24 09:31:16

标签: python formatting number-formatting

我刚试过

>>> 2.17 * 10**27
2.17e+27
>>> str(2.17 * 10**27)
'2.17e+27'
>>> "%i" % 2.17 * 10**27
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: cannot fit 'long' into an index-sized integer
>>> "%f" % 2.17 * 10**27
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: cannot fit 'long' into an index-sized integer
>>> "%l" % 2.17 * 10**27
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: incomplete format

现在我用完了想法。我想得到

2170000000000000000000000000

如何打印这么大的数字? (我不在乎它是否是Python 2.7+解决方案或Python 3.X解决方案)

1 个答案:

答案 0 :(得分:4)

您的运算符优先级错误。您正在格式化2.17,然后将其乘以一个长整数:

>>> r = "%f" % 2.17
>>> r
'2.170000'
>>> r * 10 ** 27
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: cannot fit 'long' into an index-sized integer

将括号括在乘法处:

>>> "%f" % (2.17 * 10**27)
'2169999999999999971109634048.000000'

这是为字符串格式重载模数运算符的缺点之一; Format String syntax使用的较新str.format() method及其使用的Format Specification Mini-Language(可与format() function一起使用)整齐地绕过该问题。我在这种情况下使用format()

>>> format(2.17 * 10**27, 'f')
'2169999999999999971109634048.000000'