Giacomo1968
Giacomo1968

Reputation: 26066

Converting a value from negative to positive or positive to negative in JavaScript?

I saw this answer on how to convert a negative number to positive, but have a slightly different situation: I’m doing some coding in Apache Cordova and getting accelerometer data I need to flip.

So when the accelerometer returns an X axis value of -5 I need to convert it to 5 and the opposite as well; if the X axis value is 5 the new X axis value should be -5.

I understand how to do -Math.abs() and such, but how can I accommodate a situation like this in my code?

Upvotes: 6

Views: 4954

Answers (5)

Nina Scholz
Nina Scholz

Reputation: 386578

I suggest to use the multiplication assignment with -1.

The multiplication assignment operator multiplies a variable by the value of the right operand and assigns the result to the variable. See the multiplication operator for more details.

value *= -1;

Upvotes: 2

Eric
Eric

Reputation: 3221

Why do you need Math.abs?

x_value = -1 * x_value;

works for every scenario I can envision.

Upvotes: 2

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

You can do a simple math at this context, no need of Math.abs,

x_value = x_value * -1;

Or you can negate the value like,

x_value = -(x_value);

While negating, there is a chance to get -0, But we don't need to worry about it, since -0 == 0. Abstract equality comparison algorithm is telling so in Step 1 - c - vi.

Upvotes: 9

Paulo Avelar
Paulo Avelar

Reputation: 2140

You can multiply any number by -1 to get its opposite.

Example:

 5 * -1 = -5  
-5 * -1 =  5

Upvotes: 4

Giacomo1968
Giacomo1968

Reputation: 26066

Well, my solution is to create a ternary like this to see if the x_value is greater than 0 or not and act accordingly:

x_value = x_value > 0 ? -Math.abs(x_value) : Math.abs(x_value);

Upvotes: 0

Related Questions