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

时间:2022-10-30 11:52:06

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

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

3 个解决方案

#1


222  

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

There you go. Use float (which is almost always a C double).

那就这样吧。使用float(通常是C double)。

#2


37  

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

#3


1  

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

请注意,如果您的字符串号包含超过15位有效数字,浮点数将围绕它。在这种情况下,最好使用Decimal

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

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

#1


222  

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

There you go. Use float (which is almost always a C double).

那就这样吧。使用float(通常是C double)。

#2


37  

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

#3


1  

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

请注意,如果您的字符串号包含超过15位有效数字,浮点数将围绕它。在这种情况下,最好使用Decimal

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

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