0

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:

  • If I get "288" convert it to an integer: 288.
  • If I get "0.323" convert it to a float: 0.323.
  • If I get 288 leave it as it is (its an integer already).
  • If I get 0.323 leave as it is (its a float already).

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

1
  • 1
    Why are you making a distinction between float and int? For most usecases float(value) is enough. Commented Jun 30, 2020 at 14:16

3 Answers 3

1
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
Sign up to request clarification or add additional context in comments.

Comments

1

Use following:

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

Comments

0

Would this work for you?

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.