Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

making a variable value positive

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?

like image 743
ian Avatar asked Nov 09 '09 15:11

ian


People also ask

How do you turn a negative variable into a positive?

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.

How do you make a number always positive?

Squaring a real number always makes it positive, so taking the square root of a number squared returns the positive number.

How do you make a variable positive in JavaScript?

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.


1 Answers

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.

like image 121
kemiller2002 Avatar answered Oct 15 '22 06:10

kemiller2002