Arithmetic Functions: Rounding
There are three functions in the
math module that round a float to the nearest integer. The first one we’ll take a look at is
ceil(), which is short for ceiling, and
ceil(x) returns the nearest integer greater than or equal to
If you think of the real numbers as points on a number line, when you take
ceil(x), this will round to the right, and so
ceil(x) will return the integer that’s closest to the
x but on the right of
Now, this can get a little tricky when you are dealing with negative numbers, and we’ll take a look at some examples, but if you keep the analogy of the real numbers as being points on the number line,
floor(x) rounds to the left on that number line.
x is a float and it’s got digits after the decimal point, we drop all those decimal points and keep the integer part. If we think of
x as being a point on the number line, we are rounding towards zero.
The rounding function
trunc() is a composition of
ceil(). Let me show you what I mean. Because
trunc() rounds towards zero, we can write
trunc(x) in terms of floor and ceiling depending on whether
x is greater or equal to zero or whether it’s negative.
x is a positive number—a positive float—then
trunc(x) will be rounding to the left, and so that’s equal to
floor(x). But if
x is negative, if we want to round towards zero, what we want to do is round to the right, and that’s what ceiling of
x does. So to clarify everything, let’s just look at some examples.
Let’s start off with
ceil(). Round to the right the number
5.43. Another way to think about it is that we’re rounding up. But again, think of the numbers as being the numbers on the number line. Rounding to the right with
ceil() gives us the integer
And if we round
floor(), rounding to the left gives us
-13. Now let’s use
trunc(). The truncation of
5.43, this will get rid of the decimal numbers
.43, and so we get
5. And if we do this with the negative number
-12.3, we’re getting rid of the
.3 and you get
So, those are the functions in the
math module that take an input number and round to the nearest integer. In the next lesson, we’ll take a look at a function in the
math module to help you decide when two floats are close. “How close?” depends on your relative tolerance.
Become a Member to join the conversation.