Fri Oct 22 2021·1 min read
Photo by Sebastian Pena Lambarri
To convert a negative number to a positive number, call the
method passing it the number as a parameter, e.g.
Math.abs(-10). When supplied
with a negative number, the
Math.abs method is guaranteed to return a positive
console.log(Math.abs(-5)); // 👉️ 5 console.log(Math.abs(-5.5)); // 👉️ 5.5 console.log(Math.abs(-0)); // 👉️ 0 console.log(Math.abs(1.5)); // 👉️ 1.5 console.log(Math.abs('-3.5')); // 👉️ 3.5
We used the Math.abs method to convert negative to a positive numbers.
The only parameter the method takes is the number we want to get the absolute value of.
Math.abs method returns the provided number if it's positive or zero and
the negation of the number if it's negative.
Math.absmethod, it always returns a positive number.
You might see examples online, where the number is prefixed with a minus
to invert its sign.
const num1 = -5; const num2 = 5; console.log(-num1); // 👉️ 5 console.log(-num2); // 👉️ -5
However, all this does is, it inverts the number's sign, it doesn't necessarily convert negative numbers to positive, it goes both ways.
Math.absmethod is guaranteed to give you a positive number, no matter if you pass it a positive or a negative number.
I'll send you 1 email a week with links to all of the articles I've written that week