leandro stimoli
leandro stimoli

Reputation: 21

How can I parse a string number to a float python

from excel I have a number in the following type: "22.024.833,02 ", so I've been trying .strip(), .replace() among others but I couldn't get a float from my code.

for columna, fila in mav.iterrows():
    comitente = fila['Comit.']
    moneda = fila['Especie']
    m = fila['Operado'].strip()
    m2 = m.replace('.', '')
    monto = float(m2)
    

Result: monto = float(m2) ValueError: could not convert string to float: '22024833,02'

Upvotes: 2

Views: 173

Answers (3)

FLAK-ZOSO
FLAK-ZOSO

Reputation: 4098

In Python you should use . instead of , as decimal separator.

good_float = 1.44
not_a_float = 1,22 # This will be stored as a tuple

If your input string is written with , as decimal separator, you can use String.replace() method.

>>> '3,14'.replace(',', '.')
'3.14'

If you are also using . as digit separator, you can replace it with the same method.

>>> '1.203,14'.replace('.', ' ').replace(',', '.')
'1203,14'

Then you can finely convert the string to a float using the float built-in function.

>>> float('3,14'.replace('.', ' ').replace(',', '.'))
3.14

Remember to always write .replace('.', ' ') before .replace(',', '.') to avoid a mess with periods.


Your code should work now:

>>> float(fila['Operado'].strip().replace('.', ' ').replace(',', '.'))

Upvotes: 0

Rachit Kawar
Rachit Kawar

Reputation: 74

I think this is what you are looking for

m = float(fila['Operado'].strip().replace(".","").replace(",","."))

Its better to use . for decimal places and , for the whole number part.

Upvotes: 1

CoffeeTableEspresso
CoffeeTableEspresso

Reputation: 2652

My answer is assuming you're using . for digit separator and , for the decimal point.

m = fila['Operado'].strip()    # m = "22.024.833,02"
m = m.replace('.', '')         # m = "22024833,02"
m = m.replace(',', '.')        # m = "22024833.02"
monto = float(m)               # monto = 22024833.02

Python's float expects no digit separator (the . in your example), and the decimal point to be a . (not a , as in your input).

Upvotes: 2

Related Questions