Mr.Marshal
Mr.Marshal

Reputation: 15

How can i print float values if they are float, otherwise int?

 nums = [20 , 10 , 2 , 1]
 list(map(lambda x: (x / 100) * 50, nums))

I want to get 10, 5, 1, 0.5

So, if number becomes float during calculations, i want to get float(in this case 0.5), but if it's it remains integer, I want to get number without '.0' in the end. What's the easiest way to do this in this code structure?

Upvotes: 1

Views: 142

Answers (4)

Toastlover
Toastlover

Reputation: 81

I'm unsure if this is a good solution but I think this could do the thing:

stuff = [10, 5, 1.5]
for value in stuff:
    if type(value) is int:
        print(value)
        print("done printing integer")

    elif type(value) is float:
        print(value)
        print("done printing float")

Output:

10
done printing integer
5
done printing integer
1.5
done printing float

Upvotes: 0

mozway
mozway

Reputation: 260455

You can use the is_integer method of floats.

Here using a wrapper function:

def downcast(f):
    return int(f) if f.is_integer() else f

list(map(lambda x: downcast((x / 100) * 50), nums))

output: [10, 5, 1, 0.5]

Note that this does not change how floating point arithmetic can affect the computation, for instance with 14 as input, this would still yield a 7.000000000000001, in this case you can first round to the desired precision.

Upvotes: 1

Lukas
Lukas

Reputation: 2302

Something like this?

nums = [20 , 10 , 2 , 1]
res = list(map(lambda x: (x / 100) * 50, nums))
# iterate list and change type to int when necessary - use difference between number and int(number)
res = [int(i) if i-int(i)==0 else i for i in res]
print(res)

Output:

[10, 5, 1, 0.5]

Upvotes: 0

dar rut
dar rut

Reputation: 1

I guess you have to save it into variable, and then check the type of this variable (for example: if type(output) is int... etc) Hope it helps

Upvotes: 0

Related Questions