pythonstringformatting

How do I format numbers with leading zeros efficiently in Python?


I have a set of floats in my script, and I'd like to print them from a method with a set number of leading zeros, and decimal points so that (for example): 0.0000 becomes 000.0000 12.1246 becomes 012.1245 etc.

I've tried using rjust and an f-string eg.

fX = str(str(x)).rjust(4,'0') # and
str(f'{x:0.4f}'

but can't seem to able to get the leading zeros. (I think it's the equivalent of using an Excel form 000.0000). Is there a straightforward way to do this in Python?


Solution

  • You can generalise this with the following function:

    def fmt(n: float, pre: int, post: int) -> str:
        return f"{n:0{pre+post+1}.{post}f}"
    

    Where n is your floating point value, pre is the minimum number of digits preceding the decimal point and post is the minimum number of decimal places

    print(fmt(12.1246, 3, 4))
    print(fmt(0., 3, 4))
    

    Output:

    012.1246
    000.0000