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.
Math.abs
clearly outperforms all the others. On Konqueror, bitwise (if (n < 0) n = ~n+1
) shines [the&&
variants are all bad there] andMath.abs
stinks. All in all,if (n < 0) n *= -1
andif (n < 0) n = -n
seem to be the safe ones that don't stink too badly anywhere. One problem with bitwise operators is that they force the number into a 32-bit integer - ifn
falls outside that range, the bitwise way would produce garbage. – Enhance