Round up or down to the nearest decimal

I have been building a fully functional Web Scraper for a client of mine, and they wanted me to increase all prices in an excel sheet by 18% and then round it up to the nearest quarter (.00, .25, .50, .75). I was struggling for this with a while, and was determined to solve it by myself. After a few hours of messing around on my calculator I finally figured out a solution that works for rounding up or down to the nearest decimal, so an eight, a fourth, a third.. anything. It’s pretty cool, so I thought I’d share it with ya’ll.

Let’s say you start out with $3.00, and want to multiply that by 18%, and then round it up to the nearest quarter.

3 x 1.18 = 3.54, and rounding that up to the nearest quarter makes it 3.75. Let’s see if we can figure out some type of formula to do this so we can do it programmatically.

Step 1: Multiply 3 x 1.18 = 3.54

Step 2: Multiply result (3.54) by the decimal type that you want to reach. So if you want to round up/down to the nearest eight, you’d multiply by 8. In this case we want to round up/down to the nearest quarter, so you multiply by 4. (3.54 x 4) = 14.16

Step 3: You need to choose whether you want to round up or round down. If you want to round up, use Math.Ceiling/Ceil depending on your programming language, and if you want to round down use Floor. Since we are rounding up in this case, the result is 15.

Step 4: Divide the result (15) by the decimal type you used in Step 2. So if quarter (4), eight (8), etc. In this case we are using quarters, so I multiplied 15 / 4 = 3.75.

There you go, stay tuned for more posts/tutorials.

Leave a Reply