Get the absolute value of a number in Javascript

后端 未结 5 1031
盖世英雄少女心
盖世英雄少女心 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));

提交回复
热议问题