Java Tutorial Java Advanced Java References

Java Math - copySign() Method



The Java copySign() method returns a number with magnitude of first argument and sign of second argument. The method can be overloaded and it can take double and float arguments.

Syntax

public static double copySign(double magnitude, double sign)
public static float copySign(float magnitude, float sign)

Parameters

magnitude Specify a value providing the magnitude of the result.
sign Specify a value providing the sign of the result.

Return Value

Returns a number with magnitude of first argument and sign of second argument.

Exception

NA.

Example:

In the example below, copySign() method returns a number with magnitude of first argument and sign of second argument.

public class MyClass {
 public static void main(String[] args) {
  System.out.println(Math.copySign(-324.1, 4));   
  System.out.println(Math.copySign(500, -21));
  System.out.println(Math.copySign(-40.2, -15));     
 }
}

The output of the above code will be:

324.1
-500.0
-40.2

❮ Java Math Methods