I want to remove the sign of a Number in JavaScript. Here are the test cases that I already examined at jsperf (http://jsperf.com/remove-sign-from-number)
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.
Since no better answer appeared I will summarize the findings in this answer myself.
if(n < 0) n *= -1
Is currently the best choice. It performs reasonably well on most platforms and is very readable. It also preserves the decimal fractions.n = Math.abs(n)
, might be faster on other platforms. But the gain is usually only a few percentages. You may consider detecting the browser/platform upfront and building platform-depended code that uses one or the other variant. This can give you the best performance on each platform but introduces a lot of overhead.