- Home /
how to check if a number is between one range
hello! i know that it's a stupid question, but i have to check continuosly if a number is between one range (negative number included) maybe is a elementary school question about math...
for example 0 < p < 1 or -1 < p< 1 thank's you in andvance
Answer by Sylon87 · Oct 10, 2018 at 11:36 AM
Thank’s everyone! Actually i did it by building my own method, is this
public bool IsBetween(double testValue, double bound1, double bound2)
{
return (testValue >= Math.Min(bound1,bound2) && testValue <= Math.Max(bound1,bound2));
}
If you really want a seperate method that automatically "sorts" out the $$anonymous$$ and max values this would be a better implementation:
public bool IsBetween(double testValue, double bound1, double bound2)
{
if (bound1 > bound2)
return testValue >= bound2 && testValue <= bound1;
return testValue >= bound1 && testValue <= bound2;
}
This avoids unnecessary method calls ($$anonymous$$in and $$anonymous$$ax) and also does the check if bound1 or bound2 is greater only once.
Though if you define a range it would be easier to fix the range bounds when you change that bounds so you always know which one is the smallest and which is the largest. In most cases the bounds do not change as often as you want to check if a value is in between those bounds.
Answer by jmgek · Oct 10, 2018 at 12:24 AM
var x = 30;
if (Enumerable.Range(1,100).Contains(x))
//true
if (x >= 1 && x <= 100)
//true
Answer by zamtrush · Oct 10, 2018 at 12:17 PM
public static class MathExtension
{
public static bool IsBetweenRange(this float thisValue, float value1, float value2)
{
return thisValue >= Mathf.Min(value1, value2) && thisValue <= Mathf.Max(value1, value2);
}
}
@Sylon87 check this one. use: float value = 10; value.IsBetweenRange(5, 25);
Answer by Bunny83 · Oct 10, 2018 at 12:24 AM
When you say "check" it just sound like you want to know when the number is inside the range or not. In this case just do this
if (p > minValue && p < maxValue)
{
// inside range
}
else
{
// outside range
}
if you want to keep the value within the range you can use Mathf.Clamp
p = Mathf.Clamp(p, minValue, maxValue);