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


Answers:


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

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


38
或者,更具体地说,Python浮点数是C的双精度数。
哈比人2009年

1
Bah使用float而不是double。现在我的代码被.0000000001关闭,这很痛苦
Evorlor 2014年

2
顺便说一句,这也适用于指数表示法。例如:float('7.5606e-08')产生预期的python float。
drevicko 2014年

2
使用我的python(2.7.10版),当我分配>>> x = "2342.34" 并转换为float时,>>> float(x) 我得到2342.342342.3400000000001是@Mongoose 的报告
Bruce_Warrior

使用>>> 0.1 + 0.2双。>>> 0.1 + 0.6浮动。
user1510539

50

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

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

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.