Copy sign to number

Isabelle Viktoria Maciohsek · 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

Recommended snippets

  • Number is divisible

    JavaScript, Math

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

  • Digitize number

    JavaScript, Math

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

  • Percentile of matches

    JavaScript, Math

    Calculates the percentage of numbers in the given array that are less or equal to the given value.