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"
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