Convert a Positive Number to Negative in JavaScript

avatar

Borislav Hadzhiev

Fri Oct 22 20212 min read

banner

Photo by Joshua Newton

Convert a Positive Number to Negative #

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.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee