Round to Two Decimal Places
00:00 Finally, let’s tackle those numbers after the dots and only show the two decimal digits.
00:07
Instead of printing the pure temp_cel
variable, you can put it into an f-string with curly braces, and then inside the f-string, right behind the temp_cel
variable.
00:21
You will add something in a moment, but for now you can just print it to see it still displays the same way, but you pass the string into the print()
function call.
00:31
So inside the f-string, right after the temp_cel
, you can add a colon and then .2f
.
00:40
When you add this part to your f-string, then you can see it’s displayed as 22.22
, so that’s exactly what you want.
00:52
I’ll explain this in a moment. For now, continue with the temp_far
variable. Add an f-string, add the temp_far
variable in curly braces, add a colon after temp_far
, and again .2f
.
01:05
Then the closing curly brace and a quote to close the f-string. So when you print it now, then you have the 98.60
, which is exactly what you want. With the correct result in place, have a closer look at the content of the f-string, or more specifically what’s inside the curly braces.
01:28
You have the temp_cel
and the temp_far
variables. These are expected to be floats. This will be important in a moment. So first, what is this colon in the context of an f-string?
01:40
The colon, which we have after temp_cel
and temp_far
, is used to specify a format for the expression inside of the curly braces.
01:50
Everything after the colon and before the closing curly brace describes how temp_cel
or temp_far
should be formatted.
02:00
So that’s what you do with the .2f
. This specifies the precision of the number when it’s displayed. So in this case, it’s saying that you want two digits after the decimal point. You can, for example, change a 2
to a 4
, and when you run the code, you can see that now the temp_far
variable has four digits after the zero. It’s 98.6000
.
02:26
So change it back to the 2
because that’s what you want. And then you finish the expression with the f
to tell Python that this expression should be displayed as a floating-point number.
02:37 So you display all converted temperatures rounded to two decimal places. That means the third part of this part is done, and what’s left now is prompting the user, and that’s what you will do in the next lesson.
Become a Member to join the conversation.