20
loading...
This website collects cookies to deliver better user experience
round()
and format()
methods.round()
method returns the floating-point number, the rounded version of a specified number with the specified number of decimals.# integer round off
print("Integer round off Mid value ",round(7))
# Python code to round off floating number using default value
print("Floating round off ",round(7.7))
# Python code to round off floating number with mid value
print("Floating round off Mid value ",round(7.5))
# floating number round to two decimal places
distance= 4.3847594892369461
print ("The total distance is ", round(distance,2))
Integer round off Mid value 7
Floating round off 8
Floating round off Mid value 8
The total distance is 4.38
format()
method to handle the precision of the floating-point numbers, and there are many ways to set the precision of the number in Python.%
”:- * “%
” operator is used to format as well as set precision in Python.# Python code to round to two decimals using format
# initializing value
distance= 4.7287543
# using format() to print value with 2 decimal places
print ("The value of number till 2 decimal place(using format()) is : ",end="")
print ("{0:.2f}".format(distance))
# using "%" to print value with 2 decimal places
print ("The value of number till 2 decimal place(using %) is : ",end="")
print ('%.2f'%distance)
The value of number with 2 decimal place(using format()) is : 4.73
The value of number with 2 decimal place(using %) is : 4.73