I want to remove the sign of a Number in JavaScript. Here are the test cases that I already examined at jsperf
if(n < 0) n *= -1;
if(n < 0) n = -n;
n = Math.abs(n)
(n < 0) && (n *= -1)
(n < 0) && (n = -n)
n = Math.sqrt(n*n)
According to these tests: if(n < 0) n *= -1
seems to be a good solution.
Do you know of any better, save, and more efficient way to do that?
Edit 1: Added Nikhil's Math.sqrt
case, but sqrt
is usually quite slow in most systems.
Edit 2: Jan's proposal for bitwise ops may be faster in some cases but will also remove fractional digits, and thus will not work for me.