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?
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.
You can multiply any number by -1 to get its opposite.
Example:
5 * -1 = -5
-5 * -1 = 5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With