简体   繁体   中英

How to convert exponent in Python and get rid of the 'e+'?

I'm starting with Python and I recently came across a dataset with big values. One of my fields has a list of values that looks like this: 1.3212724310201994e+18 (note the e+18 by the end of the number).

How can I convert it to a floating point number and remove the the exponent without affecting the value?

You can use Decimal from the decimal module for each element of your data:

from decimal import Decimal

s = 1.3212724310201994e+18

print(Decimal(s))

Output:

1321272431020199424

First of all, the number is already a floating point number, and you do not need to change this. The only issue is that you want to have more control over how it is converted to a string for output purposes.

By default, floating point numbers above a certain size are converted to strings using exponential notation (with "e" representing "*10^"). However, if you want to convert it to a string without exponential notation, you can use the f format specifier, for example:

a = 1.3212724310201994e+18

print("{:f}".format(a))

gives:

1321272431020199424.000000

or using "f-strings" in Python 3:

print(f"{a:f}")

here the first f tells it to use an f-string and the :f is the floating point format specifier.

You can also specify the number of decimal places that should be displayed, for example:

>>> print(f"{a:.2f}")   # 2 decimal places
1321272431020199424.00

>>> print(f"{a:.0f}")   # no decimal places
1321272431020199424

Note that the internal representation of a floating-point number in Python uses 53 binary digits of accuracy (approximately one part in 10^16), so in this case, the value of your number of magnitude approximately 10^18 is not stored with accuracy down to the nearest integer, let alone any decimal places. However, the above gives the general principle of how you control the formatting used for string conversion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM