user2839430
user2839430

Reputation: 153

Rounding Floats

So I have a simple equation that rounds a number that is imported into the function as a float. Just incase the number imported is say 53.3 it should still recognize it as an "integer" but it wasn't when I didn't set it as a float and I set it as integer because there is a "."

Any ideas?

def cm(centimeter):
    result = round(centimeter / 100, 2)
    print ("%d centimeters is the same as %d meters." % (centimeter, result))
    print (result)

cent=input("Centimeters: ")
cm(float(cent))

The problem is that this is what it outputs:

Centimeters: 53.6
53 centimeters is the same as 0 meters.
0.54

It should look like this:

Centimeters: 53.6
53.6 centimeters is the same as 0.54 meters.

Took out print(result), my bad. It still rounds it to 0 meters though when it shouldn't seeing on how result outputs as 0.54.

Upvotes: 0

Views: 199

Answers (2)

user2555451
user2555451

Reputation:

Make your function like this:

def cm(centimeter):
    result = round(centimeter / 100, 2)
    print ("%s centimeters is the same as %.2f meters." % (centimeter, result))

demo:

Centimeters: 53.6
53.6 centimeters is the same as 0.54 meters.

Also, note that I chose to use %s at the start instead of %.2f. This is so the output will display the whole input, not a rounded version. Meaning, if the user enters something like 53.006, it will show 53.006 and not 53.01.

Upvotes: 1

vinit_ivar
vinit_ivar

Reputation: 650

The issue is with your print function.

You want to say:

print ("%.2f centimeters is the same as %.2f meters." % (centimeter, result))

%d formats the variable as an integer; %f formats it as a floating-point number. The .2 sets the precision: the number of decimal places it displays till.

Upvotes: 3

Related Questions