Search code examples
pythonstringformattingstring-formatting

In Python, is there a max length float to string formatting parameter?


I have a program that prints matrices in the console which means I want the spacing for each matrix entry to be the same, regardless of how big the number is, positive or negative. I want numbers that do not need to be displayed as exponentials to not be displayed as such and floats with no non-zero decimals to be displayed without decimals. I am formatting any float number with the formatting rule:

"{: 8.3g}".format(number)

This formatting rule displays all numbers to take up exactly 8 characters, along with my preferences related to decimals and eponentials.

However, the exception to this is that very small numbers are displayed to take up 9 characters. For example:

("{: 8.3g}").format(-0.000000000000000000111) returns -1.11e-19.

I suspect it doesn't count the minus in front of the exponent but could be wrong. Any idea how to change the formatting rule to meet my requirements?


Solution

  • The width parameter is the minimal width, but if your exponent has two digits, you need a width of 9 to display the number with three significant digits as specified.

    -x.xxe-xx
    123456789
    

    If you want the numbers aligned, give a width parameter that can host all your cases:

    def f(x):
        result = f"{x: 8.3g}"
        print(f"{len(result)}: '{result}'")
    
    def g(x):
        result = f"{x: 9.3g}"
        print(f"{len(result)}: '{result}'")
    
    def h(x):
        result = f"{x: 10.3g}"
        print(f"{len(result)}: '{result}'")
    
    f(1)
    f(-1.11e-5)
    f(1.11e-10)
    f(-1.11e-100)
    print()
    g(1)
    g(-1.11e-5)
    g(1.11e-10)
    g(-1.11e-100)
    print()
    h(1)
    h(-1.11e-5)
    h(1.11e-10)
    h(-1.11e-100)
    

    Output:

    8: '       1'
    9: '-1.11e-05'
    9: ' 1.11e-10'
    10: '-1.11e-100'
    
    9: '        1'
    9: '-1.11e-05'
    9: ' 1.11e-10'
    10: '-1.11e-100'
    
    10: '         1'
    10: ' -1.11e-05'
    10: '  1.11e-10'
    10: '-1.11e-100'
    

    The sign is not to blame here. You already took care of that by using the space in the format string.