How to use Math.abs() In Javascript

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




// Javascript script to convert negative number
// to positive number
 
//Driver code
let n = -30;
let m = 15;
 
// Using Math.abs() function
n = Math.abs(n);
 
// Print result
console.log(n);
 
// Using Math.abs() function
m = Math.abs(m);
 
// Print result
console.log(m);


Output

30
15

Convert a negative number to positive in JavaScript

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:

Table of Content

  • Multiplying by -1
  • Using Math.abs()
  • adding a minus sign
  • Flipping the bit
  • Using Math.sqrt()

Similar Reads

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....

Method 2: Using Math.abs()

...

Method 3: adding a minus sign

In this method, we will use Math.abs() function to convert negative numbers to positive numbers....

Method 4: Flipping the bit

...

Method 5: Using Math.sqrt()

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....