Convert a negative number to positive in JavaScript
Last Updated :
29 Dec, 2023
In this article, we will see how we can convert a negative number to a positive number in JavaScript by the methods described below.
Below are the methods to convert a negative number to a positive in JavaScript:
Method 1: Multiplying by -1
This is a general method in which we will first check whether the number is already positive or negative, if the number is negative then we will multiply the number by -1 to make it positive.
Syntax:
if (a < 0) {
a = a * -1;
}
Example: Below is the implementation of the above approach
javascript
function convert_positive(a) {
if (a < 0) {
a = a * -1;
}
return a;
}
let n = -10;
let m = 5;
n = convert_positive(n);
console.log(n);
m = convert_positive(m);
console.log(m);
|
In this method, we will use Math.abs() function to convert negative numbers to positive numbers.
Syntax:
Math.abs(value)
Example: Below is the implementation of the above approach:
javascript
let n = -30;
let m = 15;
n = Math.abs(n);
console.log(n);
m = Math.abs(m);
console.log(m);
|
Method 3: adding a minus sign
In this method, we will check whether the number is positive or negative, if the number is negative then we add a minus sign at the beginning of the number else return the same.
Syntax:
a < 0 ? -(a) : a
Example: This example shows the above-explained approach.
Javascript
function convert_positive(a) {
return a < 0 ? -(a) : a;
}
let n = -10;
let m = 5;
n = convert_positive(n);
console.log(n);
m = convert_positive(m);
console.log(m);
|
Method 4: Flipping the bit
In this method, we will use a bit-wise not operator which flips all the bits of the number. Since the negative number is stored in a most significant bit it also flips which converts it to a positive number.
Syntax:
a < 0 ? ( ~a + 1 ) : a
Example: In this example, we Flipping the bit to Convert a negative number to positive in JavaScript.
Javascript
function convert_positive(a) {
return a < 0 ? (~a + 1) : a;
}
let n = -10;
let m = 5;
n = convert_positive(n);
console.log(n);
m = convert_positive(m);
console.log(m);
|
To convert a negative number to its positive equivalent in JavaScript using Math.sqrt()
, you can use the Math.sqrt()
function along with the Math.pow()
function.
Example: In this example, we are using Math.sqrt().
Javascript
function convertToPositive(number) {
return Math.sqrt(Math.pow(number, 2));
}
const negativeNumber = -5;
const positiveResult = convertToPositive(negativeNumber);
console.log(positiveResult);
|
Share your thoughts in the comments
Please Login to comment...