Round number

The round(x,n) method returns a rounded number x to n decimals.
The arguments:

  • x : number to round
  • n : number of decimals
x = round(1.5056, 2)

which would return 1.06

Rounding errors

You would probably round 1.85, 2.85, 3.85, 4.85 and 5.85 up, right? If you try this in a computer you won’t get that result:

print( round(1.85, 1) )
print( round(2.85, 1) )
print( round(3.85, 1) )
print( round(4.85, 1) )
print( round(5.85, 1) )
print( round(6.85, 1) )

Decimal places are not exact in a computer system, which uses base 2 instead of base 10. You can view the value that round returns with the Decimal module:

from decimal import Decimal
print( Decimal(1.85) )
print( Decimal(2.85) )
print( Decimal(3.85) )
print( Decimal(4.85) )
print( Decimal(5.85) )
print( Decimal(6.85) )

It will print the values that are stored in the computer memory. You might be surprised. These numbers are called floating points.

Round to the nearest number

Round up
If you want all floating points to be rounded up, use the math.ceil(x) method instead:

import math
print( math.ceil(2.5) )

Round down
If you want a floating point to be rounded down, you could use

import math
print( math.floor(2.5) )



Leave a Reply