Convert string to decimal number

0

Good evening,

I am having problems converting the following string to a decimal number. I extract the number from a web and it comes with. instead of with, When trying to replace the. For the, the result is the following:

x = ,,,,,

replace all the digits and not just the point.

This is my code:

x = "18.58"
if "." in x:
    x = re.sub(".", ",", x)

if x == float:
    x = round(x)

Thanks for your help

Regards,

    
asked by Xavier Villafaina 06.10.2017 в 23:04
source

1 answer

1

The problem is that the "." (Dot) by default in regex captures any character except the new line . You must escape to only literally capture the character ".":

x = "18.58"
x = re.sub("\.", ",", x)

The previous conditional is unnecessary.

You can also use str.replace :

x = "18.58"
x = x.replace(".", ",") 

However, you can not convert a string with the comma to float in Python, the decimal point is the point of fact.

To move to float you only need to apply the casting:

>>> x = "18.58"
>>> x= float(x)
>>> x
18.58
>>> x = round(x)
>>> x
19

If what you receive is a string that is a float (or an integer) with the dot as a decimal separator (which does not separate thousands) you can do what you just want with:

x = "18.58"
x = round(float(x))
    
answered by 06.10.2017 в 23:15