Format Currency (Solution)
00:00 In the previous exercise, you practiced formatting a floating-point value requesting a specific number of digits after the decimal point. Here, even though we are dealing with an integer, we can actually use the same syntax as before.
00:14 So we’ll start solving this exercise from the end. Let’s first format the given integer literal as a floating-point value with two decimal places. This automatically adds the two zeros after the decimal point, even when the number has no fractional part to begin with. Now, to group the thousands, you can include a comma in the formatting string like so.
00:39
The comma has to come before the .2f
. If the amount gets bigger by any chance, then Python will add the subsequent commas as necessary.
00:50 We’re almost there. The last point, which isn’t explicitly listed in the exercise instructions, is about adding the currency symbol. We’re working with a currency, after all.
01:01
You can combine the format()
function with an f-string literal to add that symbol. However, since we’re already using an f-string, we can just go ahead and do this all within the f-string literal.
01:20 Okay, that looks like a beautifully formatted currency to me. I’m actually quite happy with it. So let’s move on.
Become a Member to join the conversation.