Home >Backend Development >Python Tutorial >The use of round(x,[n]) in python
round(x,[n]) Round n to retain the number of decimal parts
1. When n is not filled in, the default is 0, that is, the decimal part is not retained
A. When the decimal part is only 0.5, if the integer part is an odd number Then advance by 1, and if it is an even number, discard the decimal part
print(round(1.5))#2 The decimal part is 0.5. If the integer part is an odd number, then +1
print(round(2.5))#2 The decimal part is 0.5 and the integer part is If the number is even, the decimal part is discarded
print(round(-1.5))#-2
print(round(-2.5))#-2
print(round(1.4))#1
print(round(2.4))#2
print(round(-1.4))#-1
print(round(-2.4))#-2
b. If the decimal part is not 0.5, round it off
print(round(1.54))#2 Decimal 0.54 is rounded up to 1
print(round(2.54))#3
print(round(-1.54))#-2
print(round(-2.54))#-3
print(round(1.45))#1 Decimal 0.45 Round off
print( round(2.45))#2
print(round(-1.45))#-1
print(round(-2.45))#-2
2. When the decimal part is retained
a. When the decimal part is retained after the number position When the last digit of the reserved number is 5, if the reserved number position is an even number, it will be advanced by 1, and if the odd number is discarded, it will be rounded off.
print(round(2.645, 2))#2.65 The last digit of the reserved number is 5, and the reserved position is 4, which is an even number, then 1 will be added.print(round(2.655, 2))#2.65
print(round(2.665, 2 ))#2.67
print(round(2.675, 2))#2.67
b. When the last digit of the reserved number position is not 5, round off
print(round(2.636, 2))#2.64
print(round( 2.646, 2))#2.65
print(round(2.656, 2))#2.66
print(round(2.666, 2))#2.67
print(round(2.676, 2))#2.68