Java Math copySign() Method
The copySign() method of Math class returns the first floating-point argument with the sign of the second argument.
Syntax:
public static float copySign(float magnitude, float sign)
public static double copySign(double magnitude, double sign)
Parameters:
The parameter ‘magnitude’ and ‘sign’ represents the magnitude and sign of the result.
Return Value:
The copySign() method returns a value with the magnitude of magnitude and the sign of sign.
Example 1:
public class JavaMathCopySignExample1 {
public static void main(String[] args) {
double a=8.1;
double b=-1;
//returns a value with the magnitude of 'a' and the sign of 'b'.
System.out.println("Sign and magnitude of "+ a +" : "+Math
.copySign(a,b));
}
}
Output:
Sign and magnitude of 8.1 : -8.1
Example 2:
public class JavaMathCopySignExample2 {
public static void main(String[] args) {
double a=-0.0d/0.0d;
double b=-24;
//return NaN value
System.out.println("Sign for "+ a +" value : "+Math.copySign(a,b));
}
}
Output:
Sign for NaN value : NaN
Example 3:
public class JavaMathCopySignExample3 {
public static void main(String[] args) {
float a=-0.0f;
float b=3;
//Returns the first floating-point argument with the sign of
the second floating-point argument
System.out.println("Sign and magnitude of "+ a +" = "+Math
.copySign(a,b));
}
}
Output:
Sign and magnitude of -0.0 = 0.0
Example 4:
public class JavaMathCopySignExample4 {
public static void main(String[] args) {
double x = -90d/0.0d;
double y=9;
System.out.println("Sign and magnitude = "+Math.copySign(x,y));
}
}
Output:
Sign and magnitude = Infinity
