How can I format a float with given precision and zero padding?
Asked Answered
D

3

9

I have looked at a couple of dozen similar questions - and I'm happy to just get a link to another answer - but I want to zero pad a floating point number in python 3.3

n = 2.02
print( "{?????}".format(n))
# desired output:
002.0200

The precision of the float is easy but I can't ALSO get the zero padding. What goes into the ????'s

Digamma answered 4/3, 2015 at 2:6 Comment(0)
A
14

You can use the format specifiers, like this

>>> "{:0>8.4f}".format(2.02)
'002.0200'
>>> print("{:0>8.4f}".format(2.02))
002.0200
>>> 

Here, 8 represents the total width, .4 represents the precision. And 0> means that the string has to be right aligned and filled with 0 from the left.

Ayakoayala answered 4/3, 2015 at 2:12 Comment(2)
Accepting this answer because of the extra explanation you've provided.Digamma
f-string solution: f'{2.02:08.4f}'. Side-note: The > isn't necessary; floats are right-justified by default, so you only need to specify the alignment if you want to explicitly left-justify or center the value in the field (anything but the default right justification makes no sense with zero-padding though as it will add pad zeroes on the right, making it appear more precise than the actual precision left after .4 rounding).Dairen
C
2

You can do it using both old and new formatting method for strings::

In [9]: "%08.4f" %(2.02)
Out[9]: '002.0200'

In [10]: "{:08.4f}".format(2.02)
Out[10]: '002.0200'
Coronagraph answered 4/3, 2015 at 2:32 Comment(1)
I woke up at 4 AM and had a head-palm moment when I realized that I had been trying to use "{:08.4f}".format(2.02) because I was trying to pad to two places. Completely ignoring the fact that I had to account for the full width of the expected output. Thanks for the help.Digamma
M
0

I had some problems with unaccurate floats, so here is my solution with padding the with zeroes (python 3.10). Terveisin, Markus

def float_to_string(myfloat:float, decimals:int=6)-> str:
    """ from float to string with desired number of decimals,
        if accuracy is missing use zeroes for padding
    """
    strmyfloat=str(myfloat)
    currentdecimals=strmyfloat[::-1].find('.')
    currenttens=strmyfloat.find('.')

    if currentdecimals > decimals:
        return f"{round(myfloat, decimals):.{decimals}f}"
    return strmyfloat.ljust(currenttens+1+decimals, '0')

if __name__ == '__main__':
    print(float_to_string(myfloat=-22.12))
    print(float_to_string(myfloat=22.12))
    print(float_to_string(myfloat=179.1234))
    print(float_to_string(myfloat=0.010))
    print(float_to_string(myfloat=-0.010))

    print(float_to_string(myfloat=-22.123456789))
    print(float_to_string(myfloat=22.123456789))
    print(float_to_string(myfloat=0.01000000))
Maybe answered 13/7, 2023 at 8:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.