Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding up a number so that it is divisible by 5

Tags:

c#

math

I want to round up a number (decimal) so that it's divisible by 5.

For example, I have a few numbers and the numbers after rounding up:

Number        Rounded
0.4           5
3.4           5
7.3           10

I can use ceil to convert this double to int and use a while loop to get them to the next multiple of 5, but I was wondering if there is any clever way of accomplishing this.

Thanks.

like image 476
IrishBelly Avatar asked Feb 02 '11 13:02

IrishBelly


People also ask

How do you make a number divisible by 5?

What is the Divisibility Rule of 5? The divisibility rule of 5 states that if the digit on the units place, that is, the last digit of a given number is 5 or 0, then such a number is divisible by 5. For example, in 39865, the last digit is 5, hence, the number is completely divisible by 5.

How do you know if a big number is divisible by 5?

A number is divisible by 5 if its digits last digit will be 0 or 5 . Illustration: For example, let us consider 769555 Number formed by last digit is = 5 Since 5 is divisible by 5 , answer is YES.

What function would I use to round a number up to the next number divisible by 5?

To round to the nearest 5 in Excel, you can use the MROUND function. Suppose you have a dataset as shown below where you want to round the estimated number of hours to the nearest 5. This would mean that 161 should become 160 and 163 would become 165. MROUND function takes two arguments.

How many numbers that are divisible by 5?

Here is the beginning list of numbers divisible by 5, starting with the lowest number which is 5 itself: 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, etc.


2 Answers

You could first divide by 5 and then use Math.Ceiling to round the value. Afterwards, u can multiply by 5 again.

int rounded = (int) Math.Ceiling(Number / 5) * 5
like image 189
Sören Avatar answered Nov 15 '22 14:11

Sören


If you want

 f[6]  =  10
 f[-1] =  0  
 f[-6] = -5

Sören's answer is OK.

If instead you want:

 f[6]  =  10
 f[-1] =  -5 
 f[-6] = -10  

you could do something like:

f[x_] := Sign[x] Ceiling[Abs[x]/5] * 5  

C#:

var rounded = (int) Math.Sign(x) * Math.Ceiling(Math.Abs(x)/5) * 5;
like image 22
Dr. belisarius Avatar answered Nov 15 '22 13:11

Dr. belisarius