I am getting a dynamic value. Sometimes it es 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?
I am getting a dynamic value. Sometimes it es 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?
Share Improve this question edited Jun 22, 2016 at 20:22 TylerH 21.1k77 gold badges79 silver badges112 bronze badges asked Apr 16, 2016 at 5:14 Sarower JahanSarower Jahan 1,4951 gold badge13 silver badges21 bronze badges4 Answers
Reset to default 12Use 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
You can use Math.abs(x) for getting positive value as output. Here 'x' can be any positive or negative value
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);
}
});`
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