The Wayback Machine - https://web.archive.org/web/20241129080653/https://www.geeksforgeeks.org/convert-a-negative-number-to-positive-in-javascript/
Open In App

Convert a negative number to positive in JavaScript

Last Updated : 29 Dec, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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




// Javascript script to convert negative number
// to positive number
 
// Function to convert
// given number to
// positive number
function convert_positive(a) {
    // Check the number is negative
    if (a < 0) {
        // Multiply number with -1
        // to make it positive
        a = a * -1;
    }
    // Return the positive number
    return a;
}
 
//Driver code
let n = -10;
let m = 5;
 
// Call function
n = convert_positive(n);
 
// Print result
console.log(n);
 
// Call function
m = convert_positive(m);
 
// Print result
console.log(m);


Output

10
5

Method 2: Using Math.abs()

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

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




// Javascript script
// to convert negative number
// to positive number
 
// Function to convert
// given number to
// positive number
function convert_positive(a) {
    return a < 0 ? -(a) : a;
}
 
//Driver code
let n = -10;
let m = 5;
 
// Call function
n = convert_positive(n);
 
// Print result
console.log(n);
 
// Call function
m = convert_positive(m);
 
// Print result
console.log(m);


Output

10
5

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




// Javascript script
// to convert negative number
// to positive number
 
// Function to convert
// given number to
// positive number
function convert_positive(a) {
    return a < 0 ? (~a + 1) : a;
}
 
//Driver code
let n = -10;
let m = 5;
 
// Call function
n = convert_positive(n);
 
// Print result
console.log(n);
 
// Call function
m = convert_positive(m);
 
// Print result
console.log(m);


Output

10
5

Method 5: Using Math.sqrt()

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) {
    // Using Math.sqrt() and Math.pow() to convert a negative number to positive
    return Math.sqrt(Math.pow(number, 2));
}
 
// Example usage
const negativeNumber = -5;
const positiveResult = convertToPositive(negativeNumber);
console.log(positiveResult); // Output: 5


Output

5


Previous Article
Next Article

Similar Reads

JavaScript Program to Check if a number is Positive, Negative, or Zero
In this article, we are going to learn if a number is positive, negative, or zero, for numerous mathematical operations and conditional statements in JavaScript. It is critical to know if a given number is positive, negative, or zero. This article provides a straightforward approach in JavaScript that lets you determine whether a given number belon
3 min read
JavaScript Program to Check if a Given Integer is Positive, Negative, or Zero
In this article, we will discuss how we can determine whether the given number is Positive, Negative, or Zero. As we know if the number is less than 0 then it will be called a "Negative" number if it is greater than 0 then it will be called a "Positive" number. And if it doesn't lie between them, then it will be 0. Example: Input: 10 Output: Positi
4 min read
Javascript Program to Rearrange positive and negative numbers in O(n) time and O(1) extra space
An array contains both positive and negative numbers in random order. Rearrange the array elements so that positive and negative numbers are placed alternatively. Number of positive and negative numbers need not be equal. If there are more positive numbers they appear at the end of the array. If there are more negative numbers, they too appear in t
3 min read
JavaScript Program to Count Positive and Negative Numbers in an Array
Given an array of numbers. Write a JavaScript program to count positive and negative numbers in an array. Example: Input: numbers_array1= [10,20, -1,22,99,20, -9]Output: positive no's=5, negative no's =2 Input: numbers_array2= [-121, - 78, -13, 54, -23]Output: positive no's=1, negative no's=4 Brute Force ApproachWe will be using the javascript for
2 min read
Semantic-UI Table Positive / Negative State
Semantic UI is an open-source framework that uses CSS and jQuery to build great user interfaces. It is the same as a bootstrap for use and has great different elements to use to make your website look more amazing. It uses a class to add CSS to the elements. Tables are an easy way to organize a lot of data. A table is an arrangement of data in rows
3 min read
How to get negative result using modulo operator in JavaScript ?
The %(modulo) operator in JavaScript gives the remainder obtained by dividing two numbers. There is a difference between the %(modulo) and the remainder operator. When remainder or %(modulo) is calculated on positive numbers then both behave similarly but when negative numbers are used then both behave differently. The JavaScript %(modulo) behaves
4 min read
What is negative infinity in JavaScript ?
The negative infinity in JavaScript is a constant value that is used to represent a value that is the lowest available. This means that no other number is lesser than this value. It can be generated using a self-made function or by an arithmetic operation. Note: JavaScript shows the NEGATIVE_INFINITY value as -Infinity. Negative infinity is differe
3 min read
JavaScript RangeError - Repeat count must be non-negative
This JavaScript exception repeat count must be non-negative occurs if the argument passed to String.prototype.repeat() method is a negative number. Message: RangeError: argument out of range RangeError: repeat count must be non-negative (Firefox) RangeError: Invalid count value (Chrome) Error Type: RangeError Cause of Error: The repeat() method has
1 min read
Explain the 'double negative' Trick in JavaScript
In programming, a "double negative" is a technique used to convert a value to its corresponding boolean value. This technique involves using two negation operators (!) to negate a value twice, resulting in a boolean representation of the original value. The double negative technique is often used to convert truthy and falsy values to their correspo
2 min read
Print all Negative numbers in a Range in JavaScript Array
To print all the negative numbers in a range from the JavaScript array, we need to iterate over the array and apply the condition to filter out the negative numbers. Once the elements are extracted, we can print them in the console. Example:Input: arr = [-22, 45, 63, -88, -69]Range: [-1 to -70]Output: -22, -88, -69, all negative numbers lies inside
3 min read
JavaScript Program to Print Negative Numbers in a Linked List
This JavaScript program aims to print negative numbers present in a linked list. A linked list is a data structure consisting of a sequence of elements, where each element points to the next element in the sequence. The program traverses the linked list and prints all the negative numbers encountered. Table of Content Iterative ApproachRecursive Ap
2 min read
JavaScript Program to Find the Average of all Negative Numbers in an Array
Given an array of numbers, the task is to find the average of all negative numbers present in the array. Below are the approaches to find the average of all negative numbers in an array: Table of Content Iterative ApproachFunctional Approach (Using Array Methods)Using forEach with a Separate FunctionApproach 4: Using RecursionIterative ApproachInit
4 min read
Print all Negative Numbers in JavaScript Array
In JavaScript, arrays are the data structures used to store the elements. In some cases, we need to extract the elements that satisfy the condition. To print all the negative numbers from the JavaScript array, we need to iterate over the array and apply the condition to filter out the negative numbers. Once the elements are extracted, we can print
4 min read
What is positive infinity in JavaScript ?
The positive infinity in Javascript is a number that is constant and represents a value that is the highest available. It can be generated using a self-made function or by an arithmetic operation. Note: JavaScript shows the POSITIVE_INFINITY value as Infinity. Positive Infinity: It is different from mathematical infinity in the following ways. If w
2 min read
Print all Positive Numbers in a Range in JavaScript Array
To print all the possible numbers in a range from the JavaScript array, we need to iterate over the array and apply the condition to filter out the positive numbers. Once the elements are extracted, we can print them in the console. Example:Input: arr = [-22, 45, 63, -88, -69]Range = [1 to 70]Output: 45, 63, all positive numbers lies inside the ran
3 min read
Print all Positive Numbers in JavaScript Array
In JavaScript, arrays are the data structures used to store multiple elements. In some cases, we need to extract the elements that satisfy a specified condition. We can use a condition to extract all the positive numbers from an array with the below approaches. Example:Input: arr = [-1, -12, 35, -8, 45, 68, 99]Output: 35, 45, 68, 99 all positive nu
3 min read
JavaScript Program to Print Positive Numbers in a Linked List
This JavaScript program aims to print positive numbers present in a linked list. A linked list is a data structure consisting of a sequence of elements, where each element points to the next element in the sequence. The program traverses the linked list and prints all the positive numbers encountered. Table of Content Iterative ApproachRecursive Ap
2 min read
JavaScript Program to Find the Average of all Positive Numbers in an Array
Given an array of size N, the task is to calculate and return the average of all positive elements of the given array. There are several ways to find the average of all the positive numbers in an array using JavaScript which are as follows: Table of Content Using for LoopUsing reduce methodUsing forEach Loop Using for LoopIn this approach, we are u
2 min read
How to Convert a Float Number to the Whole Number in JavaScript?
Given a float number and the task is to convert a float number to a whole number using JavaScript. Below are various methods to convert float numbers to whole numbers in JavaScript: Table of Content Math.floor (floating argument)Math.ceil (floating argument) Math.round (floating argument)Math.trunc (floating argument)parseInt (floating argument)dou
4 min read
SASS | negative variable value
SASS variables are quite useful in writing maintainable styling code for web pages. Often, we require different components of a page to have the same value for a stylistic property. In such a scenario, assigning the value to a variable and using it wherever required reduces the amount of effort needed to make changes to the styling in the future. W
2 min read
Node.js GM negative() Function
The negative() function is an inbuilt function in the GraphicsMagick library which is used to replace every pixel with its complementary color. The function returns the true value on success. Syntax: negative() Parameters: This function does not accept any parameter. Return Value: This function returns the GraphicsMagick object. Example 1: C/C++ Co
2 min read
Semantic-UI Button Variations Negative Variant
Semantic UI is an open-source framework that uses CSS and jQuery to build great user interfaces. It is the same as a bootstrap for use and has great different elements to use to make your website look more amazing. Semantic UI Button offers several types of micro button components like Types, Groups, Content, States, Variations, and Group Variation
2 min read
Semantic-UI Message Negative / Error Variation
Semantic-UI is an open-source framework that has some predefined classes to make our website look beautiful and responsive. It is similar to bootstrap as it has pre-defined classes for use. It used CSS and jQuery to build the interface. It has some different types of elements that help us to create a beautiful website. Semantic-UI Message is used t
2 min read
Primer CSS Extended Negative Margins
Primer CSS is a free open-source CSS framework that is built upon systems that create the foundation of the basic style elements such as spacing, typography, and color. This systematic method makes sure our patterns are steady and interoperable with every other. Its approach to CSS is influenced by Object-Oriented CSS principles, functional CSS, an
2 min read
Primer CSS Negative Margins
Primer CSS is a free and open-source CSS framework that is built using the GitHub design system for providing support to the broad spectrum of GitHub websites. It helps in creating the foundation of the basic style elements such as spacing, components, typography, color, etc. In this article, we'll see about Primer CSS Negative Margins. In this, we
2 min read
Semantic-UI Grid Negative Margins
Semantic UI framework is used to build an excellent user interface. It is an open-source framework that uses CSS and jQuery. This framework allows us to use various styles and properties to make a website more user-friendly. In this article, we will be seeing the Semantic UI Grid Negative Margins. Grids employ negative margins to ensure that the fi
2 min read
Can we use Padding Negative in Tailwind CSS ?
It is to be noted that Tailwind CSS doesn't support negative padding values, or in other words, there is no concept that exists for utilizing the padding value as negative. Note: Padding cannot be negative, so instead of using this, you can use negative margin. Instead of using this (negative padding), the negative margin can be used by specifying
2 min read
Bootstrap 5 Spacing Negative Margin
Bootstrap 5 Spacing Negative Margins are used to provide extended negative margins to the top and bottom of an item. With a negative margin, the n-addition is utilized before the specified size. Bootstrap 5 Spacing Negative Margin Classes: m*-n**: This class is used to set the negative margin. Where, * is representing the sides (t, b, l, r, x, and
2 min read
How to Iterate Through Numbers and Return a String Message if the Sum is Negative?
In JavaScript, iterating through numbers or any kind of iterable data structures is a common programming task. The ability to repeat a certain block of code multiple times allows you to perform operations on a set of data. We can iterate through an array of numbers and return a string message if the sum of the numbers is negative. Table of Content
5 min read
Primer CSS Negative Offset Columns
Primer CSS is a free open-source CSS framework that is built upon systems that create the foundation of the basic style elements such as spacing, typography, and color. This systematic method makes sure our patterns are steady and interoperable with every other. Its approach to CSS is influenced by Object-Oriented CSS principles, functional CSS, an
2 min read
three90RightbarBannerImg