Include the type specifier in your format expression:
>>> a = 10.1234
>>> f'{a:.2f}'
'10.12'
Answer from Robᵩ on Stack OverflowI'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
Videos
Include the type specifier in your format expression:
>>> a = 10.1234
>>> f'{a:.2f}'
'10.12'
When it comes to float numbers, you can use format specifiers:
f'{value:<width>.<precision>}'
where:
valueis any expression that evaluates to a numberwidthspecifies the number of characters used in total to display, but ifvalueneeds more space than the width specifies then the additional space is used.precisionindicates the number of characters used after the decimal point
What you are missing is the type specifier for your decimal value. In this link, you an find the available presentation types for floating point and decimal.
Here you have some examples, using the f (Fixed point) presentation type:
# notice that it adds spaces to reach the number of characters specified by width
In [1]: f'{1 + 3 * 1.5:10.3f}'
Out[1]: ' 5.500'
# notice that it uses more characters than the ones specified in width
In [2]: f'{3000 + 3 ** (1 / 2):2.1f}'
Out[2]: '3001.7'
In [3]: f'{1.2345 + 4 ** (1 / 2):9.6f}'
Out[3]: ' 3.234500'
# omitting width but providing precision will use the required characters to display the number with the the specified decimal places
In [4]: f'{1.2345 + 3 * 2:.3f}'
Out[4]: '7.234'
# not specifying the format will display the number with as many digits as Python calculates
In [5]: f'{1.2345 + 3 * 0.5}'
Out[5]: '2.7344999999999997'
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
You can use the round function, which takes as its first argument the number and the second argument is the precision after the decimal point.
In your case, it would be:
answer = str(round(answer, 2))
Using str.format()'s syntax to display answer with two decimal places (without altering the underlying value of answer):
def printC(answer):
print("\nYour Celsius value is {:0.2f}ºC.\n".format(answer))
Where:
:introduces the format spec0enables sign-aware zero-padding for numeric types.2sets the precision to2fdisplays the number as a fixed-point number