Python如何判断一个数字是否用科学计数法表示?

How does Python determine whether to represent a number using scientific notation or not?

以下是在 Python 控制台中输入的一些数字,以及结果表示:

>>> 1
1
>>> 1.234
1.234
>>> 1.234e5
123400.0
>>> 1.234e15
1234000000000000.0
>>> 1.234e25
1.234e+25

... 以下是打印相同数字时发生的情况:

>>> print 1
1
>>> print 1.234
1.234
>>> print 1.234e5
123400.0
>>> print 1.234e15
1.234e+15  # different!
>>> print 1.234e25
1.234e+25

Python 如何决定使用哪种表示法?为什么某些数字有和没有 print 会有所不同?

数值只是存储为值。 __repr__ 输出可能会根据数字的实现和类型而改变。您需要格式化数字的字符串表示形式。

示例:

>>> type(1e3) is type(1000.0) # float
True
>>> type(1e3) is type(1000)  # int
False

格式化字符串时,可以使用%g/{:g}让它自动确定最易读的格式。使用 %e/{:e} 进行明确的科学记数法。

>>> x = 1234567
>>> "{:.2e}".format(x)
1.23e+06

在Python中只有浮点数用科学记数法表示;整数总是按原样表示。

浮点数在 Python 2.7 中的表示方式取决于它是否使用 repr() (for instance, directly in the console or as a member of a collection) or str() 表示(例如使用 print 语句)。

对于 repr(),如果浮点数小于 0.0001 (1e-4) 或至少 1e16:[=24,则使用科学记数法表示=]

>>> 1e-4
0.0001
>>> 0.00009999
9.999e-05
>>> 1e16-2
9999999999999998.0
>>> 10000000000000000.0
1e+16

加上str(),上限约为1e11:

>>> print 1e11-1
99999999999.0
>>> print 100000000000.0
1e+11

注意:在Python 3中,str()现在表示浮点数的方式与repr()相同。