简体   繁体   English

如何在 Python 中格式化由宽度而不是精度分隔的浮点数?

[英]How can I format a float in Python delimited by width, not by precision?

I am looking for a way to format a number string in Python in such a way that I have a fixed width, regardless the precision.我正在寻找一种在 Python 中格式化数字字符串的方法,无论精度如何,我都有固定的宽度。 I'll give an example below:下面我举个例子:

Suppose I want to format the float for a fixed width = 8 and precision = 4. If I use the following code:假设我想将浮点数格式化为固定宽度 = 8 和精度 = 4。如果我使用以下代码:

number = 3.141516
'{:8.4f}'.format(numero)

it works well for small numbers.它适用于小数字。 But if I want to format a number like 1000000, the output is 1000000.0000 , thus giving a width greater than 8.但是如果我想格式化一个像 1000000 这样的数字,输出是1000000.0000 ,因此宽度大于 8。

Is there a way I could set the formatter in a such a way I can get a fixed width in this case?有没有一种方法可以设置格式化程序,在这种情况下我可以获得固定的宽度?

Thanks in advance提前致谢

I'm not totaly sure of what you are asking.我不完全确定你在问什么。 should the width of 8 include the dot? 8 的宽度应该包括点吗?

see if this answer your question:看看这是否能回答你的问题:

print(f'{str(float(number)) + "0"*8}'[:8])

but note that in a 7 digit integer a dot will be left by the end so you need to catch this exception.但请注意,在 7 位整数中,最后会留下一个点,因此您需要捕获此异常。 I guess by adding a 0 on front of the number and replacing the dot so it maintains the 8 width, but it depend on what you are searching.我想通过在数字前面添加一个 0 并替换点以保持 8 的宽度,但这取决于您要搜索的内容。

The width of the number also depends on the precision.数字的宽度也取决于精度。 As you want a fixed width, I would suggest you to use f strings and set the precision to be equal to the width in case the precision value is more than the width.由于您想要固定宽度,我建议您使用 f 字符串并将精度设置为等于宽度,以防精度值大于宽度。

Syntax for f strings : f'{value:{width}.{precision}}' f 字符串的语法:f'{value:{width}.{precision}}'

  • The precision includes integer + decimal value精度包括整数+十进制值

This is how you could use it:这是您可以使用它的方式:

    n = 3.141516
    print(f'{n:{8}.{4}}')

The output that you will get is:您将获得的输出是:

 3.142

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM