Reputation: 8395
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:
"288"
convert it to an integer: 288
."0.323"
convert it to a float: 0.323
.288
leave it as it is (its an integer already).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
Upvotes: 0
Views: 171
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
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
Reputation: 1366
Use following:
def convert(self, value)
a=value
b=float(a)
if(b==int(b)):b=int(b)
print(b)
Upvotes: 1