Copy sign to number

JavaScript, Math · Oct 7, 2020

Returns the absolute value of the first number, but the sign of the second.

  • Use Math.sign() to check if the two numbers have the same sign.
  • Return x if they do, -x otherwise.
const copySign = (x, y) => Math.sign(x) === Math.sign(y) ? x : -x;
copySign(2, 3); // 2
copySign(2, -3); // -2
copySign(-2, 3); // 2
copySign(-2, -3); // -2

More like this

  • Number is divisible

    Checks if the first numeric argument is divisible by the second one.

    JavaScript, Math · Sep 15, 2020

  • Primes up to given number

    Generates primes up to a given number, using the Sieve of Eratosthenes.

    JavaScript, Math · Dec 28, 2020

  • Digitize number

    Converts a number to an array of digits, removing its sign if necessary.

    JavaScript, Math · Oct 18, 2020