Returns the nearest plural

I need a function with which I can convert the number to the nearest value of a given multiplier.

For example, I want the number array to be set to a number equal to 16, so 2 = 0, 5 = 0, 11 = 16, 17 = 16, 30 = 32, etc.

thanks

+4
source share
6 answers

To do this, you need everything you need:

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

Be careful using this technique. Overloading Math.Round(double) considers the evil mutant MidpointRounding.ToEven be the best default behavior, although what we all learned earlier in school is that the CLR calls MidpointRounding.AwayFromZero . For instance:

 var x = Math.Round(1.5); // x is 2.0, like you'd expect x = Math.Round(0.5); // x is 0. WAT?! 
+23
source

16*((n+8)/16) is the formula you want if, in particular, you want to convert 8 to 16 (it is equally close to 0 to 16, so it’s impossible to decide how to convert it based solely on "near plural") concept, you have to decide! -), and, of course, sequentially from 24 to 32, from 40 to 48, etc. Use +7 instead of +8 if you prefer to convert 8 to 0 rather than 16 (and sequentially from 24 to 16, etc.).

To use generic X instead of hard-coded 16 , then the formula is X*((n+X/2)/X) (with the same condition as in the previous paragraph, if X even).

Edit : There is no need to bother with floating point numbers as other answers suggest, but you need to multiply back by X (which I mistakenly missed).

+6
source

You do not need to do floating point division, this is optional. Use the remainder operator:

 int rem = value % multiple; int result = value - rem; if (rem > (multiple / 2)) result += multiple; 
+4
source

Tilts the middle to + ∞

 int RoundNearest16(int value) { return (value + 8) & ~0xF; } 
+2
source

The case is a little more complicated if the plural is less than 1. I wrote this general function:

 public float NearestRound(float x, float delX) { if (delX < 1) { float i = (float)Math.Floor(x); float x2 = i; while ((x2 += delX) < x) ; float x1 = x2 - delX; return (Math.Abs(x - x1) < Math.Abs(x - x2)) ? x1 : x2; } else { return (float)Math.Round(x / delX, MidpointRounding.AwayFromZero) * delX; } } /* Sample: x: 101 multiple:2 NearestRound -> 102 x: 107 multiple:2 NearestRound -> 108 x: 100.9 multiple:2 NearestRound -> 100 x: 1 multiple:0.25 NearestRound -> 1 x: 1.35 multiple:0.25 NearestRound -> 1.25 x: 1.77 multiple:0.25 NearestRound -> 1.75 x: 1.9 multiple:0.25 NearestRound -> 2 */ 
0
source

In the case of rounding to the nearest multiple 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 this function as follows:

 Console.WriteLine("Convert 10.723: " + convert(10.723f, 0.5f)); // 10.5 
0
source

Source: https://habr.com/ru/post/1307883/


All Articles