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?
If version of python greater or equals to 3.6:
print(f'%.{num_decimal_places}f'%value)
Output:
20.2839280
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'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.