How To Convert A Negative Number To Positive In JavaScript?

Convert a Negative Number to Positive in JavaScript

In this article, you’ll learn how to convert a negative number to a positive in JavaScript by multiplying it by -1 or using the functions of the Math class. Let’s see the specific steps to do it below.

Convert a negative number to a positive in JavaScript

Multiplying the number by -1

There are many ways you can do that, all of them practically the same.

Using * (Multiply), it’s the same as how you’d do in Math:

Code:

const x = -5;
const y = x * -1;
console.log(y);

Output:

5

Using - (Negative, not minus), you can consider it the shorthand version of (x * -1). It’s exactly the same as how you’d do in Math:

Code:

const x = -5;
const y = -x;
console.log(y);

Output:

5

While this works fine if you know for sure the value is negative; otherwise, you might accidentally make it negative.

To deal with this, it’s required you use the Math class.

The Math class is a class that provides mathematical methods and constants (i.e. PI).

Using Math.prototype.sign()

The Math class’ .sign() function takes a number and returns its sign, but returns 0 if the number is zero.
So technically, if you take a number and multiply it by its sign, you’ll always get a positive number like the following code:

Code:

const neg = -5;
const pos = 5;
const zero = 0;

function signPostive(num) {
	console.log(num * Math.sign(num));
}

console.log(signPostive(neg)); // -5 * -1
console.log(signPostive(pos)); // 5 * 1
console.log(signPostive(zero)); // 0 * 0

Output:

5
5
0

Additionally, the .sign() function has more utility in deciding whether a number is false.

Code:

const neg = -5;
const pos = 5;
const zero = 0;

function signPostive(num) {
	if (Math.sign(num) === -1) {
		console.log(-num);
	} else {
		console.log("Is not a negative number");
	}
}

console.log(signPostive(neg));
console.log(signPostive(pos));
console.log(signPostive(zero));

Output:

5
"Is not a negative number"
"Is not a negative number"

However, this seems a little redundant, so instead, it would be better to use the Math class’ .abs() function.

Using Math.prototype.abs()

The Math class’ .abs() function takes a number and returns a positive number. It’s a stand-in for the absolute value sign, as such:

Code:

const neg = -5;
const pos = 5;
const zero = 0;

// Using the Math.prototype.abs() function, convert a negative number to a positive
console.log(Math.abs(neg));
console.log(Math.abs(pos));
console.log(Math.abs(zero));

Output:

5
5
0

Summary

To convert a negative number to a positive number in JavaScript, you need to either multiply the number by -1 or multiply that number with its sign using the Math class’ .sign() function or just use the Math class’ .abs() function. You can find documentation on the Math class’ other properties and methods here.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *