Reputation: 95
How do I get the absolute value of a number without using math.abs?
This is what I have so far:
function absVal(integer) {
var abs = integer * integer;
return abs^2;
}
Upvotes: 5
Views: 13956
Reputation: 2754
Late response, but I think this is what you were trying to accomplish:
function absVal(integer) {
return (integer**2)**.5;
}
It squares the integer then takes the square root. It will eliminate the negative.
Upvotes: 3
Reputation: 700212
You can use the conditional operator and the unary negation operator:
function absVal(integer) {
return integer < 0 ? -integer : integer;
}
Upvotes: 11
Reputation: 133403
You can also use >> (Sign-propagating right shift)
function absVal(integer) {
return (integer ^ (integer >> 31)) - (integer >> 31);;
}
Note: this will work only with integer
Upvotes: 7
Reputation: 81
Check if the number is less than zero! If it is then mulitply it with -1;
Upvotes: 0
Reputation: 15415
There's no reason why we can't borrow Java's implementation.
function myabs(a) {
return (a <= 0.0) ? 0.0 - a : a;
}
console.log(myabs(-9));
How this works:
> 0
> 0
)Upvotes: -1
Reputation: 38416
Since the absolute value of a number is "how far the number is from zero", a negative number can just be "flipped" positive (if you excuse my lack of mathematical terminology =P):
var abs = (integer < 0) ? (integer * -1) : integer;
Alternatively, though I haven't benchmarked it, it may be faster to subtract-from-zero instead of multiplying (i.e. 0 - integer
).
Upvotes: 3