我怎样才能得到一个大数的非科学记数法?

2024-04-19 00:21:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚试过

>>> 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

现在我没主意了。我想得到

^{2}$

我怎么能打印这么大的数字?(我不在乎是Python2.7+解决方案还是Python3.X解决方案)


Tags: inmoststdinlinecalllongfitfile
1条回答
网友
1楼 · 发布于 2024-04-19 00:21:04

你把你的操作员优先权弄错了。您正在格式化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

在乘法的两边加上括号:

^{pr2}$

这是为字符串格式重载module运算符的缺点之一;^{} method使用的较新的Format String syntax和它使用的Format Specification Mini-Language巧妙地避开了这个问题。对于这个例子,我将使用format()

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

相关问题 更多 >