To get the absolute value (magnitude or modulus) of a number in Java, you can use the Math.abs()
method of the java.lang.Math
class. The Math.abs()
method returns the absolute value of a number as a double.
Here is an example of how to use the Math.abs()
method to get the absolute value of a number in Java:
double number = -123.456; double absoluteValue = Math.abs(number); System.out.println("Absolute value: " + absoluteValue); // prints "Absolute value: 123.456"Sww:ecruow.lautturi.com
In this example, the Math.abs()
method returns the absolute value of the number -123.456
, which is 123.456
.
The Math.abs()
method also works with integer and long values. For example:
int number = -123; int absoluteValue = Math.abs(number); System.out.println("Absolute value: " + absoluteValue); // prints "Absolute value: 123" long number = -123L; long absoluteValue = Math.abs(number); System.out.println("Absolute value: " + absoluteValue); // prints "Absolute value: 123"
If you want to get the absolute value of a number as an integer or long, you can use the Math.abs()
method and cast the result to the desired type.
Note that the Math.abs()
method does not work with complex numbers. If you need to get the absolute value of a complex number, you can use the Complex.abs()
method of the org.apache.commons.math3.complex.Complex
class.