from platform import python_version
python_version()
'3.6.9'
'{:.0f}'.format(8.0)
'8'
'{:.0f}'.format(8.99)
'9'
'{:.2f}'.format(8.499)
'8.50'
'{:.2f}%'.format(10.12345)
'10.12%'
turn it into a string then replace everything after the second digit after the point
import re
def truncate(num,decimal_places):
dp = str(decimal_places)
return re.sub(r'^(\d+\.\d{,'+re.escape(dp)+r'})\d*$',r'\1',str(num))
truncate(8.499,decimal_places=2)
'8.49'
truncate(8.49,decimal_places=2)
'8.49'
truncate(8.4,decimal_places=2)
'8.4'
truncate(8,decimal_places=2)
'8'
# make the total string size AT LEAST 9 (including digits and points), fill with zeros to the left
'{:0>9}'.format(3.499)
'00003.499'
# make the total string size AT LEAST 2 (all included), fill with zeros to the left
'{:0>2}'.format(3)
'03'
# make the total string size AT LEAST 11 (including digits and points), fill with zeros to the RIGHT
'{:<011}'.format(3.499)
'3.499000000'
"{:,}".format(100000)
'100,000'
num = 1.12745
formatted = f"{num:.2f}"
formatted
'1.13'