Home > Software engineering >  How can i print float values if they are float, otherwise int?
How can i print float values if they are float, otherwise int?

Time:05-24

 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?

CodePudding user response:

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.

CodePudding user response:

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

CodePudding user response:

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]
  • Related