我怎样才能在非科学计数法中得到一个大数字?
How can I get a big number in non-scientific notation?
我刚试过
>>> 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 解决方案)
您的运算符优先级错误。您正在格式化 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 used by the str.format()
method and the Format Specification Mini-Language it employs (and can be used with the format()
function) 巧妙地避开了这个问题。对于这种情况,我会使用 format()
:
>>> format(2.17 * 10**27, 'f')
'2169999999999999971109634048.000000'
我刚试过
>>> 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 解决方案)
您的运算符优先级错误。您正在格式化 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 used by the str.format()
method and the Format Specification Mini-Language it employs (and can be used with the format()
function) 巧妙地避开了这个问题。对于这种情况,我会使用 format()
:
>>> format(2.17 * 10**27, 'f')
'2169999999999999971109634048.000000'