Reputation: 1495
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
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
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
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
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