Reputation: 110482
To format the number 20
as 20.00
I can do:
'%.2f' % 20.283928
'20.28'
However, I want to allow the user to be able to specify the number of decimal places. For example:
value = 20.283928
num_decimal_places = 7 # from user input
'%.%sf' % (20, '7')
How could I do something like the above?
Upvotes: 3
Views: 106
Reputation: 92461
If you are willing to use newer format
you can do this:
>>> n = 4
>>> value = 20.283928
>>> '{:.{count}f}'.format(value, count=n)
'20.2839'
Upvotes: 1
Reputation: 71610
If version of python greater or equals to 3.6:
print(f'%.{num_decimal_places}f'%value)
Output:
20.2839280
Upvotes: 3