Sarower Jahan
Sarower Jahan

Reputation: 1495

Convert negative and positive numbers to positive values

I am getting a dynamic value. Sometimes it comes with positive value and sometimes with negative value. But I always need a positive value. Is there any way to convert all negative or positive values to positive values?

Upvotes: 2

Views: 14999

Answers (4)

Deepak paramesh
Deepak paramesh

Reputation: 864

By using Math.abs(value) we will be able to do wonder.

Make a number positive

let x =  12;
let y = -12;
let resultx =  Math.abs(x); //  12
let resulty =  Math.abs(y); //  12

Make a number negative

let x =  12;
let y = -12;
let resultx = -Math.abs(x); // -12
let resulty = -Math.abs(y); // -12

Inverting a number

let x =  12;
let y = -12;
let resultx = -(x);         // -12
let resulty = -(y);         //  12

Upvotes: 0

user11006286
user11006286

Reputation:

Here is a fully functional example in addition to the answer above.

$('#amount').change(function() {
    var amount = $(this).val();
    var positive_number = Math.abs(amount);
    if (positive_number > 0) {
        $('#amount').val(positive_number);
    }
});`

Upvotes: 0

Keshav
Keshav

Reputation: 29

You can use Math.abs(x) for getting positive value as output. Here 'x' can be any positive or negative value

Upvotes: 1

Kartikeya Khosla
Kartikeya Khosla

Reputation: 18873

Use Math.abs() :

var x = -25;
alert(Math.abs(x)); //it will alert 25

Here are some test cases from the documentation:

Math.abs('-10');     // 10
Math.abs(-20);       // 20
Math.abs(null);     // 0
Math.abs("string"); // NaN
Math.abs();         // NaN

Upvotes: 12

Related Questions