In this shot, we’ll learn how to convert a negative number to a positive number in JavaScript.
We’ll start with the problem statement and then look at an example.
Given a negative integer n
, convert it to a positive integer.
Input: -20
Output: 20
We will solve this problem in two ways:
-1
.abs()
method.-1
In this approach, we’ll convert a negative integer to a positive integer by multiplying the negative integer with -1
.
//given negative integer let n = -20; //print original n console.log("Given negative integer n = " + n); //convert n to positive integer n = n * -1 //print positive n console.log("After conversion value of n = " + n)
Let’s look at the explanation of the code snippet above.
Line 2: We set the value of the integer n
as -20
.
Line 5: We print the original integer n
.
Line 8: We multiply the negative integer by -1
and assign the result to n
.
Line 11: We print the converted positive integer n
.
abs()
methodIn this approach, we’ll use a built-in method provided by the Math
module in JavaScript.
The method Math.abs()
converts the provided negative integer to a positive integer.
//given negative integer let n = -20; //print original n console.log("Given negative integer n = " + n); //convert n to positive integer n = Math.abs(n) //print positive n console.log("After conversion value of n = " + n)
Let’s look at the explanation of the code snippet above.
Line 2: We set the value of the integer n
as -20
.
Line 5: We print the original integer n
.
Line 8: We pass n
as an argument to the Math.abs()
method and assign the result to n
.
Line 11: We print the converted positive integer n
.
RELATED TAGS
CONTRIBUTOR
View all Courses