You can use the conditional operator and the unary negation operator:
function absVal(integer) {
return integer < 0 ? -integer : integer;
}
Answer from Guffa on Stack OverflowYou can use the conditional operator and the unary negation operator:
function absVal(integer) {
return integer < 0 ? -integer : integer;
}
You can also use >> (Sign-propagating right shift)
function absVal(integer) {
return (integer ^ (integer >> 31)) - (integer >> 31);;
}
Note: this will work only with integer
Videos
We have a little project where we are supposed to program absolute value without math.abs method. The question goes like this: "Suppose x and y are variables of type double. Write a program that reads in x and then sets y to the absolute value of x without calling the Math.abs() method."
Can someone help me with the code? What do you even code to accomplish this? Thank you in advance!!
I think you can probably figure this one out just with a hint.
What happens to negative numbers when they are multiplied by -1?
Note that you can check if numbers are less than zero using if and then do something about less than zero numbers.
If you still get stuck after thinking on that for a few minutes shoot me a pm.
Edit: as long as you don't ask me to just write out all the code for you.
You could just see if the number is less than 0 and then multiply it by -1
The Math.abs javascript function is designed exactly for getting the absolute value.
var x = -25;
x = Math.abs(x); // x would now be 25
console.log(x);
Here are some test cases from the documentation:
Math.abs('-1'); // 1
Math.abs(-2); // 2
Math.abs(null); // 0
Math.abs("string"); // NaN
Math.abs(); // NaN
Here is a fast way to obtain the absolute value of an integer. It's applicable on every language:
x = -25;
console.log((x ^ (x >> 31)) - (x >> 31));
However, this will not work for integers whose absolute value is greater than 0x80000000 as the >> will convert x to 32-bits.