Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 607
Giacomo1968 Avatar asked Apr 01 '16 19:04

Giacomo1968


2 Answers

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.

like image 197
Rajaprabhu Aravindasamy Avatar answered Sep 28 '22 02:09

Rajaprabhu Aravindasamy


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

Example:

 5 * -1 = -5  
-5 * -1 =  5
like image 24
Paulo Avelar Avatar answered Sep 28 '22 01:09

Paulo Avelar