Returning the nearest multiple value of a number

前端 未结 6 1625
灰色年华
灰色年华 2020-11-29 08:33

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

6条回答
  •  情话喂你
    2020-11-29 09:37

    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?!
    

提交回复
热议问题