Number.sign() in javascript

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

    A solution that works on all numbers, as well as 0 and -0, as well as Infinity and -Infinity, is:

    function sign( number ) {
        return 1 / number > 0 ? 1 : -1;
    }
    

    See the question "Are +0 and -0 the same?" for more information.


    Warning: None of these answers, including the now standard Math.sign will work on the case 0 vs -0. This may not be an issue for you, but in certain physics implementations it may matter.

提交回复
热议问题