How to detect integers in floats? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How to detect integers in floats?

Hi, i'm making a calculador as my first python project. I set he input number variables as Float, but I want an integer output if the result end with ".0". For example A + B = 27.0 --> I want an int A + B = 27.062 --> I want a float How can i change to int only integers with ".0" (type float)? Thaks

19th Mar 2021, 2:02 AM
Mnl
Mnl - avatar
3 Answers
+ 7
You can use a simple if statement. num = 27.0 if int(num) == num: print(int(num))
19th Mar 2021, 2:13 AM
ChaoticDawg
ChaoticDawg - avatar
+ 5
simple way would be c = a + b output = int(c) if c == int(c) else c
19th Mar 2021, 2:14 AM
durian
durian - avatar
+ 2
to_int_ = lambda n: n if n%1 else int(n) for x in (27, 27., 27.0, 27.065): print(to_int_(x))
19th Mar 2021, 9:03 AM
Vitaly Sokol
Vitaly Sokol - avatar