r/learnpython • u/elinoaass • Sep 17 '26
Need some help with a CSI-102 lab
ANY SUGGESTIONS ARE APPRECIATED!!! Working on a lab right now, I'm a super beginner when it comes to working with python. I'm trying to round a couple of numbers to two decimal places, and I can't figure it out. I managed to round them to whole numbers instead of a gazillion decimal places, but I need two specifically. The instructions in the lab say to "use a format specifier like {glowArea:.2f}" but I tried that and it wont work...
Here's the syntax I have so far:
PI = 3.14159265359
radius = 4.0
hitBox = round(2*radius)
glowArea = round(4*PI*radius**2)
energyCap = round(4/3*PI*radius**3)
print(f"Radius = {radius}")
print("")
print(f"Diameter (hitbox) = {hitBox}")
print(f"Glow Area = {glowArea}")
print(f"Energy Capacity = {energyCap}")Edit: its fixed now, I got rid of the rounds and also the parenthesis and then adding :.2f worked. Thanks!
View all comments
Show parent comment
2
u/xenomachina xenomachina Sep 18 '26
It isn't really
roundthat is truncating here. Theroundfunction operates on numbers, and5.9==5.90. They are the same value.If you
printa float, it is converted to a string withstr(). The behavior ofstr()on floats is the same asrepr(), which (as of Python 3.1) is to produce the shortest string that will turn into the same float value.float("5.9")==float("5.90"), so you don't get the trailing zeros.(Incidentally, this also prevents
0.1from printing as0.10000000000000001, even though the latter is a more precise representation of that float's true value. Multiply it by 3 and you'll see what I mean.)Using format specifiers like
f"{x:.2f}"or the old school"%.2f" % xsidesteps this by specifying how the string conversion should happen, including how to treat trailing zeros in the conversion. You aren't rounding the numerical value, you are changing how it is converted to a string.