I want to convert a float like a = 1.1234567
to a string, giving the precision as a second variable (which is why this is no duplicate of "Fixed digits after decimal with f-strings"):
def float2str(val, precision):
...
float2str(1.1234567, 3) # '1.123'
float2str(1.1234567, 5) # '1.12346' (mind correct rounding)
I know that f-strings can do the correct rounding using f'{a:.5f}'
, but the precision has to be part of the string.
I came up with this horribly ugly solutions and hope someone can point me to a more elegant way:
f'%.{precision}f' % a