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?
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.