Rounding Numbers
round() Function
Rounding to the nearest whole number
#
average = round(average, 2)
#
Rounding to a number of decimal places
#
interest = round(interest, 2)
#
Convert Floating Point Numbers to Integers (Higher)
round() function
# round () function will round to nearest integer
for fp in [12.8, 12.1, -12.1, -12.8]:
integer = round(fp)
print(f"{fp:5} rounds to {integer}")
12.8 rounds to 13
12.1 rounds to 12
-12.1 rounds to -12
-12.8 rounds to -13
# .5s will round to nearest even integer
for fp in [10.5, 11.5, 12.5, 13.5]:
integer = round(fp)
print(f"{fp:5} rounds to {integer}")
10.5 rounds to 10
11.5 rounds to 12
12.5 rounds to 12
13.5 rounds to 14
int() function
# int() function will remove any decimal values
# this is the same as rounding to towards zero
for fp in [12.8, 12.1, -12.1, -12.8]:
integer = int(fp)
print(f"The integer part of {fp:5} is {integer}")
#
The integer part of 12.8 is 12
The integer part of 12.1 is 12
The integer part of -12.1 is -12
The integer part of -12.8 is -12