Number.sign() in javascript

前端 未结 15 2272
日久生厌
日久生厌 2020-11-30 21:03

Wonder if there are any nontrivial ways of finding number\'s sign (signum function)?
May be shorter / faster / more elegant solutions than the obvious one



        
相关标签:
15条回答
  • 2020-11-30 21:23

    You could bit shift the number and check the Most Significant Bit (MSB). If the MSB is a 1 then the number is negative. If it is 0 then the number is positive (or 0).

    0 讨论(0)
  • 2020-11-30 21:24

    More elegant version of fast solution:

    var sign = number?number<0?-1:1:0
    
    0 讨论(0)
  • 2020-11-30 21:28

    For people who are interested what is going on with latest browsers, in ES6 version there is a native Math.sign method. You can check the support here.

    Basically it returns -1, 1, 0 or NaN

    Math.sign(3);     //  1
    Math.sign(-3);    // -1
    Math.sign('-3');  // -1
    Math.sign(0);     //  0
    Math.sign(-0);    // -0
    Math.sign(NaN);   // NaN
    Math.sign('foo'); // NaN
    Math.sign();      // NaN
    
    0 讨论(0)
  • 2020-11-30 21:29

    I just was about to ask the same question, but came to a solution before i was finished writing, saw this Question already existed, but didn't saw this solution.

    (n >> 31) + (n > 0)

    it seems to be faster by adding a ternary though (n >> 31) + (n>0?1:0)

    0 讨论(0)
  • 2020-11-30 21:30

    Dividing the number by its absolute value also gives its sign. Using the short-circuiting logical AND operator allows us to special-case 0 so we don't end up dividing by it:

    var sign = number && number / Math.abs(number);
    
    0 讨论(0)
  • 2020-11-30 21:36
    var sign = number >> 31 | -number >>> 31;
    

    Superfast if you do not need Infinity and know that the number is an integer, found in openjdk-7 source: java.lang.Integer.signum()

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