Skip to content Skip to sidebar Skip to footer

Python Convert String To Float Or Int Dynamically

I have a string that I have to convert into int or float depending or the case : What I have => What I want '548189848.54' => 548189848.54 '548189848.50' => 548189848.5

Solution 1:

Here's a one line that should do it.

numbers = ["548189848.54", "548189848.50", "548189848.00"]
result= [int(float(x)) if int(float(x)) ==float(x) elsefloat(x)  for x in numbers]

Gives output:

print result
[548189848.54, 548189848.5, 548189848]

Solution 2:

Maybe you could convert to float and then use round:

inputs = [ "548189848.54", "548189848.50", "548189848.00" ]

for i in inputs:
    f = float(i)
    ifround(f) == f:
        printint(f)
    else:
        print f

output:

548189848.54
548189848.5
548189848

You could also do the same thing using a list comprehension, like:

print [int(float(i)) ifround(float(i)) == float(i) elsefloat(i) for i in inputs]

output:

[548189848.54, 548189848.5, 548189848]

Solution 3:

num_str = "548189848.54"if'.'in num_str:
    num = float(num_str)
else:
    num = int(num_str)

Solution 4:

str_a = "23423.00"

a = float(str_a)
if a % 1.0 == 0:
    a = int(a)

Solution 5:

You just have to do that:

a = float("548189848.54")
a = int(a) ifabs(int(a) - a) == 0else a

Post a Comment for "Python Convert String To Float Or Int Dynamically"