Get the absolute value of a number in Javascript

后端 未结 5 956
盖世英雄少女心
盖世英雄少女心 2020-12-13 08:34

I want to get the absolute value of a number in JavaScript. That is, drop the sign. I know mathematically I can do this by squaring the number then taking the square root, b

相关标签:
5条回答
  • 2020-12-13 08:43

    Here is a fast way to obtain the absolute value of a number. It's applicable on every language:

    x = -25;
    console.log((x ^ (x >> 31)) - (x >> 31));

    0 讨论(0)
  • 2020-12-13 08:43

    Alternative solution

    Math.max(x,-x)
    

    let abs = x => Math.max(x,-x);
    
    console.log( abs(24), abs(-24) );

    Also the Rick answer can be shorted to x>0 ? x : -x

    0 讨论(0)
  • 2020-12-13 09:00

    You mean like getting the absolute value of a number? The Math.abs javascript function is designed exactly for this purpose.

    var x = -25;
    x = Math.abs(x); // x would now be 25 
    console.log(x);

    Here are some test cases from the documentation:

    Math.abs('-1');     // 1
    Math.abs(-2);       // 2
    Math.abs(null);     // 0
    Math.abs("string"); // NaN
    Math.abs();         // NaN
    
    0 讨论(0)
  • 2020-12-13 09:01

    I think you are looking for Math.abs(x)

    https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Math/abs

    0 讨论(0)
  • 2020-12-13 09:06

    If you want to see how JavaScript implements this feature under the hood you can check out this post.

    Blog Post

    Here is the implementation based on the chromium source code.

    function MathAbs(x) {
      x = +x;
      return (x > 0) ? x : 0 - x;
    }
    
    console.log(MathAbs(-25));

    0 讨论(0)
提交回复
热议问题