EN
Java - Math.abs() method example
3
points
The Math.abs()
function returns the absolute value of a number.
The absolute value of the number x denoted |x|, is the non-negative value of x without regard to its sign.
Popular usage examples:
public class MathExample {
public static void main(String[] args) {
System.out.println( Math.abs(2) ); // 2
System.out.println( Math.abs(-2) ); // 2
System.out.println( Math.abs(2.54) ); // 2.54
System.out.println( Math.abs(-2.54) ); // 2.54
System.out.println( Math.abs(0) ); // 0
System.out.println( Math.abs(3 + 5) ); // 8
System.out.println( Math.abs(3 - 5) ); // 2
}
}
1. Documentation
Syntax |
|
Parameters | number - double , float , int , or long value (primitive value). |
Result | The absolute value calculated from the number (primitive value). |
Description |
|
2. Math.abs() custom implementation
public class CustomMath {
static double abs(double x) {
if (x < 0) {
return -x;
}
return x;
}
public static void main(String[] args) {
System.out.println( abs(2.0) ); // 2.0
System.out.println( abs(-2.0)); // 2.0
System.out.println( abs(0.0) ); // 0.0
}
}
Note: there are few ways to change sign to opposite if(x < 0)
istrue
:
x = -x
x *= -1
x = ~x + 1
(not for double)