float upto 2 decimal in python code example
Example 1: how to print a float with only 2 digits after decimal in python
#to round floats in Python you can use the "round" function. ex:
tax = 34.4563
tax = round(tax, 2)
#the number 2 at the end is how many digits are rounded.
#the variable "tax" would now be: 34.46
Example 2: printing with format float to 2 decimal places python
formatted_float = "{:.2f}".format(a_float)
Example 3: finding 2 decimal places python
a_float = 3.14159
formatted_float = "{:.2f}".format(a_float)
Example 4: print 2 decimal places python
print("{0:.2f}".format(sum(query_marks)/len(query_marks)))
Example 5: round off float to 2 decimal places in python
answer = str(round(answer, 2))
Example 6: how to round to 1 decimal place in python
# Some numerical values
valueA = 3.14159265359
valueB = 1845.7409947
valueC = -100.95
valueD = 9.5432
valueE = 34.49953
# Round to different decimal places
roundA = round(valueA, 5)
roundB = round(valueB, 4)
roundC = round(valueC, 3)
roundD = round(valueD, 2)
roundE = round(valueE, 1)
# Output rounded values
print("Value:".ljust(15), "Rounded:")
print(str(valueA).ljust(15), roundA)
print(str(valueB).ljust(15), roundB)
print(str(valueC).ljust(15), roundC)
print(str(valueD).ljust(15), roundD)
print(str(valueE).ljust(15), roundE)