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
288leave it as it is (its an integer already). - If I get
0.323leave 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
float(value)is enough.