Convert a negative number to a positive one in JavaScript

Convert a negative number to a positive one in JavaScript

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

Solutions/Answers:

Solution 1:

You could use this…

Math.abs(x)

Math​.abs() | MDN

Solution 2:

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

Solution 3:

Math.abs(x) or if you are certain the value is negative before the conversion just prepend a regular minus sign: x = -x.

Solution 4:

The minus sign (-) can convert positive numbers to negative numbers and negative numbers to positive numbers. x=-y is visual sugar for x=(y*-1).

var y = -100;
var x =- y;

Solution 5:

unsigned_value = Math.abs(signed_value);

Solution 6:

var posNum = (num < 0) ? num * -1 : num; // if num is negative multiple by negative one ... 

I find this solution easy to understand.

Related:  javascript Rich Text Editors