Another approach is to utilize f-strings and their ability to manipulate strings. First I present the method, then walk through it
def format_float_string(string_value: str, num_decimals: int) -> str:
# Split the input string into its integer and decimal parts
number, decimal = string_value.split('.')
# Format the integer part
formatted_integer = f"{int(number):d}"
# Format the decimal part with the specified number of decimal places
formatted_decimal = f"{int(decimal[:num_decimals]):0<{num_decimals}}"
return f"{formatted_integer}.{formatted_decimal}"
# Test the function with an example value
test_string = "97.17312522036036245646"
test_decimals = 5
format_float_string(test_string, test_decimals) ----> '97.17312'
format_float_string(test_string, 30) ----> '97.173125220360362456460000000000'
Knowing a string representation of a float we can split the number in into the integer and fractional bits. Only the fractional bit needs to be formatted, where we can use num_decimals
to cut off at the the desired digit by indexing the string. The of the number of decimals are higher than the actual string representation it will be filled with zeros.