简体   繁体   English

如何在 Python 中转换指数并去掉“e+”?

[英]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.我从 Python 开始,我最近遇到了一个具有大值的数据集。 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).我的一个字段有一个如下所示的值列表: 1.3212724310201994e+18 (注意数字末尾的e+18 )。

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:您可以对数据的每个元素使用Decimal模块中的decimal

from decimal import Decimal

s = 1.3212724310201994e+18

print(Decimal(s))

Output: 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.唯一的问题是您希望更好地控制如何将其转换为用于 output 目的的字符串。

By default, floating point numbers above a certain size are converted to strings using exponential notation (with "e" representing "*10^").默认情况下,超过一定大小的浮点数使用指数表示法转换为字符串(“e”代表“*10^”)。 However, if you want to convert it to a string without exponential notation, you can use the f format specifier, for example:但是,如果要将其转换为不带指数表示法的字符串,则可以使用f格式说明符,例如:

a = 1.3212724310201994e+18

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

gives:给出:

1321272431020199424.000000

or using "f-strings" in Python 3:或在 Python 3 中使用“f-strings”:

print(f"{a:f}")

here the first f tells it to use an f-string and the :f is the floating point format specifier.这里第一个f告诉它使用 f 字符串, :f是浮点格式说明符。

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.请注意,Python 中浮点数的内部表示使用 53 位二进制精度(大约 10 ^ 16 的一部分),因此在这种情况下,您的大约 10 ^ 18 的数量值不会准确存储直到最近的 integer,更不用说任何小数位了。 However, the above gives the general principle of how you control the formatting used for string conversion.但是,上面给出了如何控制用于字符串转换的格式的一般原则。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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