How to Convert Negative Number to Positive Number in Javascript

  • Post category:Javascript
  • Reading time:2 mins read

This post help you to solve your query related to converting negative value to positive value in Javascript.

Convert Negative Number to Positive Number in Javascript

Using Math.abs() method, we can easily convert negative number to positive number in Javascript. Let’s understand this using the example given below.

let amount = prompt("Enter a value");
let total = 2000 - amount;
let result = Math.abs(total);
if (amount == 2000) {
  console.log("Thank you for purchasing the phone");
} else if (amount > 2000) {
  console.log(`Alert! You are paying $ ${result} more for the phone`);
} else {
  console.log(`You need to pay $ ${result} more to buy this phone`);
}
When I enter 2200 then output will be.
Output: Alert! You are paying $ 200 more for the phone

In this code, when I enter a value of more than 2000 then I will get the output value positive. But, if I don’t use the Math.abs() and enter a value of more than 2000 then I will get the output value negative.

In line number 2, suppose, If I entered a value of 2200. Then 2000-2200 will become -200 value. So, this value will be stored in the total variable, and in this case else if statement will work. So, it will execute the code written in the else if statement.

So, In this way, You can convert a negative number to a positive one in JavaScript.

Share this