有没有一种简单的方法可以用Python字符串来修正小数点之后的数字数?(特别是f-字符串,而不是像.format或%这样的其他字符串格式选项)
例如,假设我想在小数位之后显示2位数字。
我该怎么做?就这么说吧
a = 10.1234发布于 2017-07-25 17:50:11
在格式表达式中包括类型说明符:
>>> a = 10.1234
>>> f'{a:.2f}'
'10.12'发布于 2018-05-14 23:17:53
当涉及到float数字时,可以使用格式说明符
f'{value:{width}.{precision}}'其中:
value是计算为数字的任何表达式。width指定要显示的字符总数,但是如果value需要比宽度指定的更多空间,则使用额外的空间。precision表示小数点之后使用的字符数。您缺少的是您的十进制值的类型说明符。在这个链接中,您可以找到浮点数和小数点的可用表示类型。
这里有一些示例,使用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'发布于 2018-09-27 10:10:24
添加到Robᵩ的答案:如果您想打印相当大的数字,使用千分隔符可能是一个很大的帮助(注意逗号)。
>>> f'{a*1000:,.2f}'
'10,123.40'如果您想要填充/使用固定宽度,宽度在逗号之前为:
>>> f'{a*1000:20,.2f}'
' 10,123.40'https://stackoverflow.com/questions/45310254
复制相似问题