Number.sign() in javascript

前端 未结 15 2273
日久生厌
日久生厌 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:41

    My two cents, with a function that returns the same results as Math.sign would do, ie sign(-0) --> -0, sign(-Infinity) --> -Infinity, sign(null) --> 0, sign(undefined) --> NaN, etc.

    function sign(x) {
        return +(x > -x) || (x && -1) || +x;
    }
    

    Jsperf won't let me create a test or revision, sorry for not being able to provide you with tests (i've given jsbench.github.io a try, but results seem much closer to one another than with Jsperf...)

    If someone could please add it to a Jsperf revision, I would be curious to see how it compares to all the previously given solutions...

    Thank you!

    Jim.

    EDIT:

    I should have written:

    function sign(x) {
        return +(x > -x) || (+x && -1) || +x;
    }
    

    ((+x && -1) instead of (x && -1)) in order to handle sign('abc') properly (--> NaN)

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

    I thought I'd add this just for fun:

    function sgn(x){
      return 2*(x>0)-1;
    }
    

    0 and NaN will return -1
    works fine on +/-Infinity

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

    Very similar to Martijn's answer is

    function sgn(x) {
        isNaN(x) ? NaN : (x === 0 ? x : (x < 0 ? -1 : 1));
    }
    

    I find it more readable. Also (or, depending on your point of view, however), it also groks things that can be interpreted as a number; e.g., it returns -1 when presented with '-5'.

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