TL;DR
print('The sales amount is $', format(salesAmount, '.2f'))
Breaking it down:
Convert the number to string formatted as 2 decimal places (.2 portion) with floating point representation (f portion).
format(salesAmount, '.2f')
Now that you have a string, you join it with either pass to print or you could join to previous code with + or whatever.
'The sales amount is $' + the_formatted_number
Answer from JBernardo on Stack Overflowpython - Need help understanding the format ".2f" command and why it is not working in my code - Stack Overflow
Pythonic way to show 2 decimal places in f-strings?
Do the second one, just donโt worry about rounding it. Let the formatting do the rounding for display.
More on reddit.comUsing an f-string with multiple parameters (decimal places plus string padding)
What is %0.2f?
Is the format to print just 2 decimals instead of all of them when you print a float
More on reddit.comTL;DR
print('The sales amount is $', format(salesAmount, '.2f'))
Breaking it down:
Convert the number to string formatted as 2 decimal places (.2 portion) with floating point representation (f portion).
format(salesAmount, '.2f')
Now that you have a string, you join it with either pass to print or you could join to previous code with + or whatever.
'The sales amount is $' + the_formatted_number
.2f should be outside of the format method.
eg try print("{:.2f}".format(12.345678))
I've got a number that needs to be rounded to 2 decimal places. Getting the round is easy, but if the number is a whole number or only has 1 digit beyond the decimal the rounding doesn't properly show 2 decimal places.
answer = 1 print(round(float(answer),2)) >> 1.0
I really like f-strings, so I would use this:
answer = 1
print(f"{round(float(answer),2):.2f}")
>> 1.00
Is there a neater or more readable method of doing this?
Do the second one, just donโt worry about rounding it. Let the formatting do the rounding for display.
Also, formatting to round things is one instance where I sometimes prefer the .format() method to fstrings, as you can define the formatting once and use it again and again:
>>> FORMAT_2DP = "{:.2f}"
>>> numbers = 1, 3, 4, 5
>>> for number in numbers:
... print(FORMAT_2DP.format(number))
...
1.00
3.00
4.00
5.00