Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

fstring float to int with leading zeros

I need to generate a string from a float which is always the length of 5.
For example:

input_number: float = 2.22
output_str = "00222"

The float never larger then 999.xx and can have an arbitrary number of decimal places.
I came up with the following code, but I doubt whether what I have in mind can’t be done in a more pythonic way.

My solution:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

input_number = 343.2423423
input_rounded = round(input_number, 2)
input_str = str(input_rounded)
input_str = input_str.replace(".","")
input_int = int(input_str)
output_str = f"{input_int:05d}"

More examples:

343.2423423 -> "34324"
23.3434343 -> "02334"

>Solution :

Does this matches your use cases:

for input_number in (343.2423423, 23.3434343, 0.34, .1):
    num, decimal = str(input_number).split('.')
    print(f"{num.zfill(3)}{decimal[:2].ljust(2, '0')}")

Out:

34324
02334
00034
00010
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading