Reputation: 2164
Here are some numbers entered in the Python console, and the resulting representations:
>>> 1
1
>>> 1.234
1.234
>>> 1.234e5
123400.0
>>> 1.234e15
1234000000000000.0
>>> 1.234e25
1.234e+25
... and here's what happens when the same numbers are printed:
>>> 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
How does Python decide which representation to use? Why is it different with and without print
for some numbers?
Upvotes: 2
Views: 2092
Reputation: 59238
Only floating point numbers are represented using scientific notation in Python; integers are always represented as-is.
How a floating point number is represented in Python 2.7 depends on whether it's represented using repr()
(for instance, directly in the console or as a member of a collection) or str()
(e.g. with the print
statement).
With repr()
, floating point numbers are represented using scientific notation if they are either less than 0.0001
(1e-4
) or at least 1e16
:
>>> 1e-4
0.0001
>>> 0.00009999
9.999e-05
>>> 1e16-2
9999999999999998.0
>>> 10000000000000000.0
1e+16
With str()
, the upper limit is approximately 1e11
:
>>> print 1e11-1
99999999999.0
>>> print 100000000000.0
1e+11
Note: in Python 3, str()
now represents floating point numbers in the same way as repr()
.
Upvotes: 5
Reputation: 4681
Numeric values are just stored as values. The __repr__
output may change based on the implementation and type of number. You need to format the string representation of a number.
Example:
>>> type(1e3) is type(1000.0) # float
True
>>> type(1e3) is type(1000) # int
False
When you format a string, you can use %g
/{:g}
to have it automatically determine the most readable format. Use %e
/{:e}
for explicit scientific notation.
>>> x = 1234567
>>> "{:.2e}".format(x)
1.23e+06
Upvotes: 2