Python 用 f 字符串固定小数点后的数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45310254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Fixed digits after decimal with f-strings
提问by GafferMan2112
Is there an easy way with Python f-strings to fix the number of digits after the decimal point? (Specifically f-strings, not other string formatting options like .format or %)
Python f-strings 是否有一种简单的方法来修复小数点后的位数?(特别是 f 字符串,而不是其他字符串格式选项,如 .format 或 %)
For example, let's say I want to display 2 digits after the decimal place.
例如,假设我想在小数点后显示 2 位数字。
How do I do that? Let's say that
我怎么做?让我们说
a = 10.1234
回答by Rob?
Include the type specifier in your format expression:
在格式表达式中包含类型说明符:
>>> a = 10.1234
>>> f'{a:.2f}'
'10.12'
回答by lmiguelvargasf
When it comes to float
numbers, you can use format specifiers:
当涉及到float
数字时,您可以使用格式说明符:
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
value
是任何计算结果为数字的表达式width
指定要显示的总共使用的字符数,但如果value
需要比指定的宽度更多的空间,则使用额外的空间。precision
表示小数点后使用的字符数
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:
这里有一些使用f
(固定点)演示类型的示例:
# 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'
回答by Bouncner
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).
添加到 Rob? 的答案:如果您想打印相当大的数字,使用千位分隔符会很有帮助(注意逗号)。
>>> f'{a*1000:,.2f}'
'10,123.40'
回答by Nicolas Gervais
Use format specifiers with f strings(more here).
将格式说明符与f 字符串一起使用(更多信息请点击此处)。
- You can control the number of decimals:
- 您可以控制小数位数:
pi = 3.141592653589793238462643383279
print(f'The first 6 decimals of pi are {pi:.6f}.')
The first 6 decimals of pi are 3.141593.
- You can convert to percentage:
- 您可以转换为百分比:
grade = 29/45
print(f'My grade rounded to 3 decimals is {grade:.3%}.')
My grade rounded to 3 decimals is 64.444%.
- You can do other things like print constant length:
- 您可以执行其他操作,例如打印常量长度:
from random import randint
for i in range(5):
print(f'My money is {randint(0, 150):>3}$')
My money is 126$
My money is 7$
My money is 136$
My money is 15$
My money is 88$
- Or even print with a comma thousand separator:
- 甚至用逗号千位分隔符打印:
print(f'I am worth {10000000000:,}$')
I am worth 10,000,000,000$
回答by Rahul Sharma
a = 10.1234
print(f"{a:0.2f}")
in 0.2f:
在 0.2f:
- 0 is telling python to put no limit on the total number of digits to display
- .2 is saying that we want to take only 2 digits after decimal (the result will be same as a round() function)
- f is telling that it's a float number. If you forget f then it will just print 1 less digit after the decimal. In this case, it will be only 1 digit after the decimal.
- 0 告诉 python 不限制显示的总位数
- .2 是说我们只想取小数点后的 2 位数字(结果将与 round() 函数相同)
- f 表示它是一个浮点数。如果你忘记了 f 那么它只会在小数点后少打印 1 位数字。在这种情况下,小数点后只有 1 位数字。
A detailed video on f-string for numbers https://youtu.be/RtKUsUTY6to?t=606
关于数字 f-string 的详细视频 https://youtu.be/RtKUsUTY6to?t=606
回答by Kevin
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
输出:2000/01/30 15:10:15.001