round() Function
Rounding to the nearest whole number
1 2 3 | # average = round (average, 2 ) # |
Rounding to a number of decimal places
1 2 3 | # interest = round (interest, 2 ) # |
Convert Floating Point Numbers to Integers (Higher)
round() function
1 2 3 4 | # 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
1 2 3 4 | # .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
1 2 3 4 5 6 | # 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