What I want to do is quite simple in itself, but I'm wondering is there is some really neat and compact way of accomplishing the same thing.
I have a float variable, and I want to check if it's value is between 0 and 1. If it's smaller than 0 I want to set it to zero, if it's larger than 1 I want to set it to 1.
Usually I do this:
// var myVar is set before by some calculation
if(myVar > 1){
myVar = 1;
}
if(myVar < 0){
myVar = 0;
}
Does anyone know of a more elegant/compact way of doing this?
If x is in range, then it must be greater than or equal to low, i.e., (x-low) >= 0. And must be smaller than or equal to high i.e., (high – x) <= 0. So if result of the multiplication is less than or equal to 0, then x is in range.
You can check if a number is present or not present in a Python range() object. To check if given number is in a range, use Python if statement with in keyword as shown below. number in range() expression returns a boolean value: True if number is present in the range(), False if number is not present in the range.
In Excel, to check if a value exists in a range or not, you can use the COUNTIF function, with the IF function. With COUNTIF you can check for the value and with IF, you can return a result value to show to the user. i.e., Yes or No, Found or Not Found.
ValueRange. of(minValue, maxValue); range. isValidIntValue(x); it returns true if minValue <= x <= MaxValue - i.e. within the range.
The mutate() function from the dplyr package also allows us to check if a value is between a range. The dplyr mutate() function adds a column to our data frame specifying if the value is in range (TRUE) or not (FALSE).
One possible solution:
myVar = Math.min(1, Math.max(0, myVar));
Another:
myVar = myVar < 0 ? 0 : myVar > 1 ? 1 : myVar;
Use Math.min and Math.max, and avoid having a condition.
var MAX = 100;
var MIN = 50;
var val = 75;
console.log( Math.max(MIN, Math.min(MAX, val)) );
var val = 49;
console.log( Math.max(MIN, Math.min(MAX, val)) );
var val = 101;
console.log( Math.max(MIN, Math.min(MAX, val)) );
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