Erica
Erica

Reputation: 201

How do I print a float as an integer?

This is for a homework assignment in my Python class that I am having an issue on. I am not allowed to import anything or use try-except.

I want to take 3 numbers and print the smallest one without using the min() function. The issue I am having is that if the number is something like 5 it gets printed as 5.000000 because I converted all the numbers to floats. I tried using rstrip('0') and it prints it as 5. which makes sense, but I need integers to be printed as an integer and floats to be printed as a float. Is there a simpler way to do this that I am missing?

My code for reference:

def min3(num1, num2, num3):
if (num1 <= num2):
    if(num1 <= num3):
        return num1
    else:
        return num3

if (num2 <= num1):
    if(num2 <= num3):
        return num2
    else:
        return num3

def main():
    num1 = float(input("Please enter the first number: "))
    num2 = float(input("Please enter the second number: "))
    num3 = float(input("Please enter the third number: "))

    smallest_num = min3(num1, num2, num3)
    print("The smallest number is %f." %(smallest_num))

main()

Upvotes: 0

Views: 82

Answers (1)

Borys Serebrov
Borys Serebrov

Reputation: 16172

You can do something like this

if smallest_num.is_integer():
   # print as integer
   print "The smallest is %d" % smallest_num
else:
   # print as float
   print "The smallest is %f" % smallest_num

Upvotes: 1

Related Questions