I have a variable that will sometimes be negative and sometimes positive.
Before I use it I need to make it positive. How can I accomplish this?
Multiply with Minus One to Convert a Positive Number All you have to do just multiply a negative value with -1 and it will return the positive number instead of the negative.
Squaring a real number always makes it positive, so taking the square root of a number squared returns the positive number.
To convert a negative number to a positive one in JavaScript, use the abs() method in JavaScript. The method returns the absolute value of a number.
Use the Math.abs method.
There is a comment below about using negation (thanks Kelly for making me think about that), and it is slightly faster vs the Math.abs
over a large amount of conversions if you make a local reference to the Math.abs
function (without the local reference Math.abs
is much slower).
Look at the answer to this question for more detail. Over small numbers the difference is negligible, and I think Math.abs is a much cleaner way of "self documenting" the code.
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