xxxxxxxxxx
num = 123.4567
formatted_num = '{0:.2f}'.format(num) # to 2 decimal places
# formatted_num = '123.46'
xxxxxxxxxx
print(format(432.456, ".2f"))
>> 432.45
print(format(321,".2f"))
>> 321.00
xxxxxxxxxx
float = 2.154327
format_float = "{:.2f}".format(float)
print(format_float)
xxxxxxxxxx
#larryadah
# This is my favorite option
num = 987.654321
rounded_num = round(num, 2) # to 2 decimal places
print(rounded_num) # rounded_num = 987.65
print(type(rouned_num)) # the rounded value remains a 'float'
# However, a second option could be
num = 987.654321
rounded_num = '{0:.2f}'.format(num) # to 2 decimal places
print(rounded_num) # rounded_num = '987.65'
print(type(rouned_num)) # the rounded value becomes a 'string'
#larryadah
xxxxxxxxxx
>>> foobar = 3.141592
>>> print(f'My number is {foobar:.2f} - look at the nice rounding!')
My number is 3.14 - look at the nice rounding!