CKTIS / Java
Math.abs(double) — absolute value and tolerance
Find the absolute difference between two `double` values and check whether it falls within a tolerance, including at the boundary.
Version: Java SE 21
Syntax
public static double abs(double a)
// Invocation with a double argument:
double magnitude = Math.abs(a);Math.abs(double) is a static method of java.lang.Math. It takes a double and returns a double. For finite nonzero values, it leaves positive values unchanged and negates negative values. A double argument expression selects this overload rather than the float, int, or long overload.
Both +0.0 and -0.0 return positive zero (0.0). Either infinity returns positive infinity, and NaN returns NaN.
To compare two amounts regardless of which is larger, use Math.abs(actual - expected) <= tolerance with a finite, nonnegative tolerance. Subtraction gives the signed difference, Math.abs gives its magnitude, and <= includes the boundary. If the result of Math.abs is NaN or positive infinity, the comparison with such a tolerance is false.
Subtraction with double values can round the result; Math.abs does not undo that rounding. When amounts require exact decimal arithmetic, use BigDecimal constructed directly from decimal text.
Examples
public class AmountTolerance {
public static void main(String[] args) {
double actual = 19.75;
double expected = 20.0;
double tolerance = 0.25;
double difference = Math.abs(actual - expected);
boolean withinTolerance = difference <= tolerance;
System.out.println(difference);
System.out.println(withinTolerance);
}
}Result
0.25 true
`19.75 - 20.0` is `-0.25`. The method returns `0.25`, so `0.25 <= 0.25` is `true`.
Related lessons
- Java · Lesson 19 · Intermediate · Version: 2