问题
Is there an easy way with Python f-strings (PEP 498) to fix the number of digits after the decimal point? (Specifically f-strings, not other string formatting options like .format or %)
For example, let's say I want to display 2 digits after the decimal place.
How do I do that?
a = 10.1234
f'{a:.2}'
Out[2]: '1e+01'
f'{a:.4}'
Out[3]: '10.12'
a = 100.1234
f'{a:.4}'
Out[5]: '100.1'
As you can see "precision" has changed meaning from "number of places after the decimal point" as is the case when using % formatting, to just total digits. How can I always get 2 digits after the decimal, no matter how big a number I have?
回答1:
Include the type specifier in your format expression:
>>> a = 10.1234
>>> f'{a:.2f}'
'10.12'
回答2:
When it comes to float
numbers, you can use format specifiers:
f'{value:{width}.{precision}}'
where:
value
is any expression that evaluates to a numberwidth
specifies the number of characters used in total to display, but ifvalue
needs more space than the width specifies then the additional space is used.precision
indicates 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'
回答3:
Adding to Robᵩ's answer: in case you want to print rather large numbers, using thousand separators can be a great help (note the comma).
>>> f'{a*1000:,.2f}'
'10,123.40'
回答4:
For rounding...
import datetime as dt
now = dt.datetime(2000, 1, 30, 15, 10, 15, 900)
now_mil = round(now.microsecond/1000)
print(f"{now:%Y/%m/%d %H:%M:%S.}{now_mil:03}")
Output: 2000/01/30 15:10:15.001
来源:https://stackoverflow.com/questions/45310254/fixed-digits-after-decimal-with-f-strings