You should use the new format specifications to define how your value should be represented:
>>> from math import pi # pi ~ 3.141592653589793
>>> '{0:.2f}'.format(pi)
'3.14'
The documentation can be a bit obtuse at times, so I recommend the following, easier readable references:
- the Python String Format Cookbook: shows examples of the new-style
.format()string formatting - pyformat.info: compares the old-style
%string formatting with the new-style.format()string formatting
Python 3.6 introduced literal string interpolation (also known as f-strings) so now you can write the above even more succinct as:
>>> f'{pi:.2f}'
'3.14'
Answer from BioGeek on Stack OverflowYou should use the new format specifications to define how your value should be represented:
>>> from math import pi # pi ~ 3.141592653589793
>>> '{0:.2f}'.format(pi)
'3.14'
The documentation can be a bit obtuse at times, so I recommend the following, easier readable references:
- the Python String Format Cookbook: shows examples of the new-style
.format()string formatting - pyformat.info: compares the old-style
%string formatting with the new-style.format()string formatting
Python 3.6 introduced literal string interpolation (also known as f-strings) so now you can write the above even more succinct as:
>>> f'{pi:.2f}'
'3.14'
The String Formatting Operations section of the Python documentation contains the answer you're looking for. In short:
"%0.2f" % (num,)
Some examples:
>>> "%0.2f" % 10
'10.00'
>>> "%0.2f" % 1000
'1000.00'
>>> "%0.2f" % 10.1
'10.10'
>>> "%0.2f" % 10.120
'10.12'
>>> "%0.2f" % 10.126
'10.13'
Add a decimal point with number of digits .2f see the docs: https://docs.python.org/2/library/string.html#format-specification-mini-language :
In [212]:
"{0:,.2f}".format(2083525.34561)
Out[212]:
'2,083,525.35'
For python 3 you can use f-strings (thanks to @Alex F):
In [2]:
value = 2083525.34561
f"{value:,.2f}"
Out[2]:
'2,083,525.35'
("%.2f" % 2083525.34561).replace(".", ",")
Formatting commas with 2 decimals PYTHON - Stack Overflow
How to use the float() command to create 2 decimal places instead of one in a product of 2 numbers [the product is dollar amount]
How to format to two decimal places python
How do I put commas between numbers?
Videos
Example:
hourlyRate = 20 hoursLabor = 1.6
I want the answer to show โ32.00โ instead of โ32โ or โ32.0โ.
What I have so far produces the number 32.0:
totalPay = float(hourlyRate * hoursLabor)
print(totalPay)
Iโm obviously very new at this. Just getting some beginnerโs practice :)
I want to format a float so that it will round to two decimal places, but I am not sure how to do that. Can someone help me? I tried using round() but it doesn't work.
Let's say I have 2792819, now I want it to be like 2,792,819. How do I do it?
I can do so while reversing it and after every 3 iterations, put a comma or something like that. But is there a better way to do so?