In Java, Math.copySign(magnitude, sign) returns a number with the size of magnitude and the sign of sign. Math.copySign(12.5, -1.0) is -12.5.
It reads the sign bit directly, so it can even see the sign of -0.0. Typical uses: giving a speed a direction, building rounding rules that are symmetric around zero, and detecting negative zero.
A static method of the java.lang.Math class, added in Java 6 (JDK 1.6). Call it on the class name, as in Math.copySign(...). No import is needed, because classes in java.lang are always visible.
Syntax
Pass the value whose size you keep, then the value whose sign you copy.
Java
double v = Math.copySign(12.5, -1.0); // -12.5
double w = Math.copySign(-3.0, 2.0); // 3.0
double z = Math.copySign(7.0, -0.0); // -7.0
float f = Math.copySign(7.0f, -2f); // -7.0
Call
What it does
Math.copySign(5.0, -0.1)
Returns -5.0.
Math.copySign(-5.0, 9.0)
Returns 5.0 (sign replaced, not combined).
Math.copySign(1.0, x)
1.0 or -1.0, telling apart 0.0 and -0.0.
Math.copySign(Math.floor(Math.abs(x) + 0.5), x)
Round half away from zero.
The sign is copied, not multiplied: a negative magnitude with a positive sign becomes positive. This differs from Math.abs(m) * Math.signum(s), which gives 0 when s is zero.
Library declarations
Java
// java.lang.Math
public static double copySign(double magnitude, double sign)
public static float copySign(float magnitude, float sign)
Parameters
Parameter
Description
magnitude
Supplies the size (absolute value) of the result.
sign
Supplies only the sign of the result, including the sign of a zero.