12

Possible Duplicate:
Python - Parse String to Float or Int

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

Community
  • 1
  • 1
Bunny Rabbit
  • 7,957
  • 15
  • 62
  • 103

2 Answers2

28

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.

Daniel DiPaolo
  • 53,439
  • 13
  • 112
  • 113
  • 2
    Of course, a `float` isn't a `decimal` and will have trouble with some decimal numbers. –  Jul 22 '11 at 19:00
5

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

For example:

float('1.03')
agf
  • 160,324
  • 40
  • 275
  • 231
  • 1
    int('1.03') is going fail, though. You'll need something like int(float('1.03')) for that. – Alex Apr 13 '16 at 08:11