How to convert decimal string in python to a number?

Possible Duplicate:
Python - Parse String to Float or Int

How can I convert '1.03' (string) to a number in Python, preferably a decimal ?


Just use float()

>>> float('1.03')
1.03

If you need an actual Decimal type, use the decimal module:

>>> from decimal import *
>>> Decimal('1.03')
Decimal('1.03')

In general, using floats will be easier for you, but you pay for that with the inexact precision that comes with floats.


float , int , and decimal can automatically convert valid strings.

For example:

float('1.03')
链接地址: http://www.djcxy.com/p/48420.html

上一篇: 如何将字符串转换为浮点型?

下一篇: 如何将python中的十进制字符串转换为数字?