Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a negative number to a positive one in JavaScript

Tags:

javascript

Is there a math function in JavaScript that converts numbers to positive value?

like image 641
dave Avatar asked Jan 10 '11 22:01

dave


People also ask

How do I change a negative number to positive in JavaScript?

To convert a negative number to a positive one in JavaScript, use the abs() method in JavaScript. The method returns the absolute value of a number.

How do you turn a negative into a positive?

All you have to do just multiply a negative value with -1 and it will return the positive number instead of the negative.


2 Answers

You could use this...

Math.abs(x) 

Math​.abs() | MDN

like image 85
ChrisNel52 Avatar answered Oct 05 '22 15:10

ChrisNel52


What about x *= -1? I like its simplicity.

like image 22
gnclmorais Avatar answered Oct 05 '22 14:10

gnclmorais