Rounding Down
00:00 In the previous lesson, I showed you the algorithm for rounding up. In this lesson, I’ll cover the obvious next choice rounding down. Rounding down uses a similar approach to rounding up, but instead of going to the next integer, greater than or equal to, it goes down to the previous integer.
00:19 Consider 12.345 once more. This time, rounding down. Rounding to the tens place drops the two to a zero. The ones gets rid of everything to the right of the decimal no matter what that is. Tenths, and then hundredths does the same.
00:36
Let’s look at some code to implement rounding down. To round up, I used the ceiling function from the math library. The companion to ceil()
is logically enough the floor. floor
()` of 1.2 is one, and of negative 0.5 is negative one.
01:00
For positive numbers, the floor()
is the same as truncation, but for negative numbers, it’s not. Let’s use floor()
to write a function that rounds down.
01:12
The approach here is very similar to rounding up, except the ceil()
method gets replaced with a call to floor()
. Let’s try this out. Importing it
01:34 1.37 for the tenths is 1.3,
01:40 and because I’m flooring, -0.5 adds left, which is negative one. Okay, you’ve seen a couple of algorithms now. Before proceeding to some more, let’s take a bit of a detour to talk about how to evaluate the different approaches to rounding.
Become a Member to join the conversation.