Convert a Positive Number to Negative in JavaScript

Borislav Hadzhiev

Fri Oct 22 2021·2 min read

Photo by Joshua Newton

**To convert a positive number to a negative number, prefix a call to the
Math.abs() method with a minus, e.g. -Math.abs(10). When prefixed with a
minus, the Math.abs method will always return a negative number.**

index.js

`console.log(-Math.abs(10)); // 👉️ -10 console.log(-Math.abs(10.5)); // 👉️ -10.5 console.log(-Math.abs(-10)); // 👉️ -10`

We used the Math.abs method to convert positive to a negative numbers.

The only parameter the method takes is the number we want to get the absolute value of.

The method returns the absolute value of a number, in other words it returns the number's distance from zero.

Here are some examples.

index.js

`console.log(Math.abs(-5)); // 👉️ 5 console.log(Math.abs(5)); // 👉️ 5 console.log(Math.abs('5')); // 👉️ 5`

The `Math.abs`

method returns the provided number if it's positive or zero and
the negation of the number if it's negative.

By default the method always returns a positive number, so by prefixing it with a minus

`-`

, we are guaranteed to get a negative number back.An alternative approach is to use multiply by `-1`

.

**To convert a positive number to a negative number, multiply the number by
-1, e.g. 5 * -1. By multiplying the number by -1, we flip the number's
sign and get back a negative number.**

index.js

`console.log(10 * -1); // 👉️ -10 console.log(10.5 * -1); // 👉️ -10.5 console.log(-10 * -1); // 👉️ 10`

Notice however that our third example is different from when we used the

`Math.abs`

method. We multiplied a negative number by `-1`

and got back a positive number.By multiplying a number by `-1`

, we just flip its sign.

To avoid this scenario, use the `Math.abs`

method prefixed with a minus. This
guarantees you that even if a negative number is provided, a negative number
will be returned.

Use the search field on my Home Page to filter through my more than 1,000 articles.