如何在Python中将字符串转换为双精度?

问题:如何在Python中将字符串转换为双精度?

我想知道如何将包含数字的字符串转换为双精度型。

I would like to know how to convert a string containing digits to a double.


回答 0

>>> x = "2342.34"
>>> float(x)
2342.3400000000001

妳去 使用float(其行为类似于C,C ++或Java double,并且具有相同的精度)。

>>> x = "2342.34"
>>> float(x)
2342.3400000000001

There you go. Use float (which behaves like and has the same precision as a C,C++, or Java double).


回答 1

十进制运算符可能更符合您的要求:

>>> from decimal import Decimal
>>> x = "234243.434"
>>> print Decimal(x)
234243.434

The decimal operator might be more in line with what you are looking for:

>>> from decimal import Decimal
>>> x = "234243.434"
>>> print Decimal(x)
234243.434

回答 2

请注意,如果您的字符串数字包含的有效位数超过15个,float(s)则将其取整。在这种情况下,最好使用Decimal

这是一个解释和一些代码示例:https : //docs.python.org/3/library/sys.html#sys.float_info

Be aware that if your string number contains more than 15 significant digits float(s) will round it.In those cases it is better to use Decimal

Here is an explanation and some code samples: https://docs.python.org/3/library/sys.html#sys.float_info