fstring float to int with leading zeros

Question:

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:

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"

Asked By: sebwr

||

Answers:

Here is one way to do it:

for input_number in (343.2423423, 23.3434343, 0.34, .1, 23.45, 2.32):
    num, decimal = str(input_number).split('.')
    formatted_num = "{:03d}".format(int(num))
    formatted_decimal = "{:.2f}".format(float("0."+decimal))[2:]
    print(formatted_num+formatted_decimal)
Answered By: David Meu

Does this match 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
Answered By: Maurice Meyer

This is the simplest way I can think of. Format it into a string with two decimal places shown and six total characters (left-filling with zeroes), then remove the decimal point.

def format_number(number):
    return f'{number:06.2f}'.replace('.', '')

The format specification mini-language can seem pretty arcane, but in this case it’s just:

  • 0: the character to fill with
  • 6: the total number of characters to produce (including the decimal)
  • .2: the number of digits to show after the decimal
  • f: fixed-point float notation
Answered By: CrazyChucky
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.