Search code examples
pythonpython-3.xformatnumber-formatting

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. 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:

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.

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


Solution

  • 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.

    Syntax for f strings: 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