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
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.
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.
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.
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.
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
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?!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With