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'
Since this post might be here for a while, lets also point out python 3 syntax:
"{:.2f}".format(5)
You could use the string formatting operator for that:
>>> '%.2f' % 1.234
'1.23'
>>> '%.2f' % 5.0
'5.00'
The result of the operator is a string, so you can store it in a variable, print etc.
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.comHow 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 to get float to two decimal places without rounding off.
Videos
You are running into the old problem with floating point numbers that not all numbers can be represented exactly. The command line is just showing you the full floating point form from memory.
With floating point representation, your rounded version is the same number. Since computers are binary, they store floating point numbers as an integer and then divide it by a power of two so 13.95 will be represented in a similar fashion to 125650429603636838/(2**53).
Double precision numbers have 53 bits (16 digits) of precision and regular floats have 24 bits (8 digits) of precision. The floating point type in Python uses double precision to store the values.
For example,
>>> 125650429603636838/(2**53)
13.949999999999999
>>> 234042163/(2**24)
13.949999988079071
>>> a = 13.946
>>> print(a)
13.946
>>> print("%.2f" % a)
13.95
>>> round(a,2)
13.949999999999999
>>> print("%.2f" % round(a, 2))
13.95
>>> print("{:.2f}".format(a))
13.95
>>> print("{:.2f}".format(round(a, 2)))
13.95
>>> print("{:.15f}".format(round(a, 2)))
13.949999999999999
If you are after only two decimal places (to display a currency value, for example), then you have a couple of better choices:
- Use integers and store values in cents, not dollars and then divide by 100 to convert to dollars.
- Or use a fixed point number like decimal.
There are new format specifications, String Format Specification Mini-Language:
You can do the same as:
"{:.2f}".format(13.949999999999999)
Note 1: the above returns a string. In order to get as float, simply wrap with float(...):
float("{:.2f}".format(13.949999999999999))
Note 2: wrapping with float() doesn't change anything:
>>> x = 13.949999999999999999
>>> x
13.95
>>> g = float("{:.2f}".format(x))
>>> g
13.95
>>> x == g
True
>>> h = round(x, 2)
>>> h
13.95
>>> x == h
True
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
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 :)