How to convert negative numbers to positive numbers in JavaScript
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.
Problem
Given a negative integer n, convert it to a positive integer.
Example
Input: -20
Output: 20
Solution
We will solve this problem in two ways:
- Multiply the number with
-1. - Use the
abs()method.
Multiply with -1
In this approach, we’ll convert a negative integer to a positive integer by multiplying the negative integer with -1.
Implementation
//given negative integerlet n = -20;//print original nconsole.log("Given negative integer n = " + n);//convert n to positive integern = n * -1//print positive nconsole.log("After conversion value of n = " + n)
Explanation
Let’s look at the explanation of the code snippet above.
-
Line 2: We set the value of the integer
nas-20. -
Line 5: We print the original integer
n. -
Line 8: We multiply the negative integer by
-1and assign the result ton. -
Line 11: We print the converted positive integer
n.
Use the abs() method
In 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.
Implementation
//given negative integerlet n = -20;//print original nconsole.log("Given negative integer n = " + n);//convert n to positive integern = Math.abs(n)//print positive nconsole.log("After conversion value of n = " + n)
Explanation
Let’s look at the explanation of the code snippet above.
-
Line 2: We set the value of the integer
nas-20. -
Line 5: We print the original integer
n. -
Line 8: We pass
nas an argument to theMath.abs()method and assign the result ton. -
Line 11: We print the converted positive integer
n.