SinfonierDominante
SinfonierDominante

Reputation: 71

Fix returned number

I want to know how to clamp/range/fix (I don't know how to call it) a number.

For exmaple, I want to always fix a number into multiple of 10 so it should works like this:

If you get number: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 must be fixed at 0.

If you get number: 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 must be fixed at 10.

If you get number: 20, 21, 22, 23, 24, 25, 26, 27, 28, 29 must be fixed at 20.

And so on.

I know that it must be easy but I can't find out by myself, thank you in advise.

Upvotes: 0

Views: 72

Answers (1)

AKX
AKX

Reputation: 168913

Divide by the desired precision (e.g. 10) -- integer division always floors values, i.e. returns the smallest integer for the division -- and then multiply again with the same precision.

public static int FloorToPrecision(int value, int precision) {
  return (value / precision) * precision;
} 

e.g. Console.WriteLine(FloorToPrecision(17, 10)); prints out 10.

Upvotes: 3

Related Questions