# Ex5 and rounding to 2 decimal places

I am going through the book lp3thw again from the start as I had taken some time off. I have come to ex5 and have been working on the study drills and I wanted to take the 2 converted values and have them displayed as a rounded number to 2 decimal places. After a bit of wading around in the documentation and using google I came across:

``print(round(i,4))``

Giving me the ability to round a float.

Great, this sounds like what I want to do. So I tried various ways of incorporating `round` into the `print` statement with no success. In the end I decided to just create variables called `weight_kg_rounded` and `height_cm_rounded` and just do the math in there and then print the rounded number.

What I eventually ended up with was this:

``````name = 'Graham Hand'
age = 39 #not a lie!
height = 74 #inches, lie!
height_cm = height * 2.54
height_cm_rounded = round(height_cm,2)
weight = 180 #lbs.....total lie
weight_kg = weight / 2.2
weight_kg_rounded = round(weight_kg,2)
eyes = 'Blue'
teeth = 'present'
hair = 'Grey'

print(f"Let's talk about {name}.")
print(f"He's {height} inches tall.")
print(f"He weigh's {weight} pounds.")
print("Actually, that's not too heavy")
print(f"He's got {eyes} eyes and {hair} hair.")
print(f"His teeth are all {teeth}.")
print(f"He is {height_cm} tall in centimetres")
print(f"He is {weight_kg_rounded} in kilograms")

#This line is tricky, try to get it exactly right.
total = age + height + weight
print(f"If I add {age}, {height}, and {weight} I get {total}")``````

This is me mucking around for my own curiosity, I realize it’s not exactly as the example in the book but there ya go.

Anyone have any other suggestions on how to do this?

int()
Do int({weight}) etc, wherever you need to round the floats.

1 Like

Ahhhhhhhh floating point. So two things help with getting accurate floating point:

https://docs.python.org/3/library/decimal.html

And also:

You can either use Decimal and get it exact, or add a format specifier when you print and get what you want on output.

1 Like

you can use round() like this;

print(f"He is {round(height_cm, 2)} tall in centimetres")
print(f"He is {round(weight_kg, 2)} in kilograms")

1 Like