Avión
Avión

Reputation: 8395

Converting strings into float and integers (if is necessary) in Python

I've to call an API that sometimes returns me numerical values in string format, "288" instead of 288, or "0.1523" instead of 0.1513. Some other times, I get the proper numerical value, 39.

How can I make the function to format it to the proper value? This means:

This is my try. The thing is that this also converts me all the floats into integers, and I don't want this. Can someone give me hand?

def parse_value(value):
    try:
       value = int(value)
    except ValueError:
        try:
            value = float(value)
        except ValueError:
            pass

Thanks in advance

Upvotes: 0

Views: 171

Answers (3)

Presbitero
Presbitero

Reputation: 128

Would this work for you?

def parse_value(value):
    f = float(value)
    r = f if f != int(f) else int(f)
    return r

Upvotes: 0

Umair Mubeen
Umair Mubeen

Reputation: 843

def parse_value(value):
    try:
       print(type(value))
       if type(value) is float:
           print(value)
       elif type(value) is int:
           print(value)
       elif type(value) is str:
           value = float(value)
           print(value)

    except ValueError:
        try:
           print(value)
        except ValueError:
            pass

Upvotes: 1

Sanket Singh
Sanket Singh

Reputation: 1366

Use following:

def convert(self, value)
    a=value
    b=float(a)
    if(b==int(b)):b=int(b) 
    
    print(b)

Upvotes: 1

Related Questions