最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Convert negative and positive numbers to positive values - Stack Overflow

programmeradmin1浏览0评论

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 badges
Add a ment  | 

4 Answers 4

Reset to default 12

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
发布评论

评论列表(0)

  1. 暂无评论