Convert a negative number to positive in JavaScript
We can convert a negative number to a positive number in javascript by the methods described below.
Method 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 with -1 to make it positive.
Syntax:
if (a < 0) {
a = a * -1;
}
Example: Below is the implementation of the above approach:
<script> // 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 var n = -10; var m = 5; // Call function n = convert_positive(n); // Print result document.write(n + "<br>"); // Call function m = convert_positive(m); // Print result document.write(m + "<br>"); </script> |
Output:
10 5
Method 2: In this method we will use Math.abs() function to convert negative number to positive number.
Syntax:
Math.abs(value)
Example: Below is the implementation of the above approach:
<script> // Javascript script // to convert negative number // to positive number //Driver code var n = -30; var m = 15; // Using Math.abs() function n = Math.abs(n); // Print result document.write(n + "<br>"); // Using Math.abs() function m = Math.abs(m); // Print result document.write(m + "<br>"); </script> |
Output:
30 15
Recommended Posts:
- How to convert a pixel value to a number value using JavaScript ?
- How to convert a float number to the whole number in JavaScript?
- Convert boolean result into number/integer in JavaScript
- What is negative infinity in JavaScript?
- What is positive infinity in JavaScript?
- How to get negative result using modulo operator in JavaScript ?
- How to Convert Array to Set in JavaScript?
- How to convert Set to Array in JavaScript?
- How to convert decimal to hex in JavaScript ?
- How to convert a JavaScript date to UTC?
- Convert string into date using JavaScript
- How to convert PHP array to JavaScript or JSON ?
- How to convert a plain object into ES6 Map using JavaScript ?
- How to convert date to another timezone in JavaScript ?
- Convert an Array to an Object in JavaScript
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


