Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning the nearest multiple value of a number

Tags:

c#

I need a function by which I will be able to convert a number to a nearest value of a given multiple.

Eg i want an array of number to be set to the neareast multiple of 16, so 2 = 0, 5 = 0, 11 = 16, 17 = 16, 30 = 32 etc

thanks

like image 557
mouthpiec Avatar asked Apr 24 '10 17:04

mouthpiec


People also ask

How do I find the nearest multiple of a number?

Given two numbers n and x, we need to calculate the smallest value of x that is closest to given number n. We need to find a k such that x*k is closest to n. If we do k = n/x, we get a value of k that may not lead to maximum.

How do you find the nearest multiple of 5?

If you need to round a number to the nearest multiple of 5, you can use the MROUND function and supply 5 for number of digits. The value in B6 is 17 and the result is 15 since 15 is the nearest multiple of 5 to 17.

How do you round to the nearest multiple of a number in Python?

Use round(number) to round to the nearest multiple of 5 Divide the number by 5. Call round(a_number) on the result a_number to get an int . Multiply that int by 5 to get the nearest multiple.

How do you find the nearest multiple of 10?

Let's round down the given number n to the nearest integer which ends with 0 and store this value in a variable a. a = (n / 10) * 10. So, the round up n (call it b) is b = a + 10. If n - a > b - n then the answer is b otherwise the answer is a.


2 Answers

In case of rounding of to the nearest multiple of a float, you can use this:

public static float convert(float value, float multipleOf) 
{
    return (float) Math.Round((decimal)value / (decimal)multipleOf, MidpointRounding.AwayFromZero) * multipleOf;
}

Then you can use the function like this:

Console.WriteLine("Convert 10.723: " + convert(10.723f, 0.5f)); // 10.5
like image 115
Xpleria Avatar answered Oct 12 '22 23:10

Xpleria


Some division and rounding should be all you need for this:

int value = 30;
int factor = 16;
int nearestMultiple = 
        (int)Math.Round(
             (value / (double)factor),
             MidpointRounding.AwayFromZero
         ) * factor;

Be careful using this technique. The Math.Round(double) overload believes the evil mutant MidpointRounding.ToEven is the best default behavior, even though what we all learned before in school is what the CLR calls MidpointRounding.AwayFromZero. For example:

var x = Math.Round(1.5); // x is 2.0, like you'd expect
x = Math.Round(0.5); // x is 0. WAT?!
like image 39
Aaronaught Avatar answered Oct 13 '22 01:10

Aaronaught