views:

147

answers:

4

how to convert -1 to 1 with javascript ?

var count = -1; //or any other number -2 -3 -4 -5 ...

or

var count = 1; //or any other number 2 3 4 5 ...

result should be

var count = 1; //or any other number 2 3 4 5 ...
+15  A: 
 count = Math.abs(count)
 // will give you the positive value of any negative number
webdestroya
+3  A: 

The abs function turns all numbers positive: i.e Math.abs( -1 ) = 1

ianhales
+3  A: 

Alternative approach (might be faster then Math.abs, untested):

count = -5;
alert((count ^ (count >> 31)) - (count >> 31));

Note that bitwise operations in javascript are always in 32-bit.

ChristopheD
[A test](http://jsfiddle.net/ZS5KC/)
Peter Ajtai
In FF3.6 your code is 6% slower than Math.abs (the fastest method in FF3.6), and compared to `v < 0 ? -v : v` (the fastest in the other tested browsers) your code is 1% slower in Opera 3.6, 12% slower in Chrome 6.0 and 20% slower in IE8.
some
In the comment above I meant Opera 10.63.
some
A: 

If the number of interest is input... In addition to Math.abs(input)....

var count = (input < 0 ? -input : input);

jsFiddle example

(edit: as Some pointed out -input is faster than -1 * input)

The above makes use of the Javascript conditional operator. This is the only ternary (taking three operands) Javascript operator.

The syntax is:

condition ? expr1 : expr2

If the condition is true, expr1 is evaluated, if it's fales expr2 is evaluated.

Peter Ajtai
If not using Math.abs (the cleanest way to show what you want to do, and also the fastest in FF3.6) try `v < 0 ? v * -1 : v` instead, it's faster than *-1.
some
@some - How is what I have... `input < 0 ? input * -1 : input` different from ------------------------ `v < 0 ? v * -1 : v` ?
Peter Ajtai
Sorry, that should be `v < 0 ? -v : v`. That's the fastest one in Opera 10.63, Chrome 6.3 and IE8. `Math.abs(v)` is fastest in Firefox 3.6.
some
You want to know how much slower? About 1,4% in opera 10.63, about 2% in FF3.6, about 1% in IE8. In Chrome 6.3 the difference is too small to measure.
some
@some - thanks, that's interesting - updated.
Peter Ajtai