Java Math.abs() 絕對值

Math.abs() 方法用於取得數值的絕對值(非負數值)。

語法

Math.abs(int a)
Math.abs(long a)
Math.abs(float a)
Math.abs(double a)

基本用法

// int
System.out.println(Math.abs(10));    // 10
System.out.println(Math.abs(-10));   // 10
System.out.println(Math.abs(0));     // 0

// double
System.out.println(Math.abs(3.14));   // 3.14
System.out.println(Math.abs(-3.14));  // 3.14

// long
System.out.println(Math.abs(-100L));  // 100

// float
System.out.println(Math.abs(-2.5f));  // 2.5

注意事項

整數溢位問題

// Integer.MIN_VALUE 的絕對值會溢位
System.out.println(Integer.MIN_VALUE);           // -2147483648
System.out.println(Math.abs(Integer.MIN_VALUE)); // -2147483648(溢位!)

// 安全的做法
System.out.println(Math.absExact(Integer.MIN_VALUE)); // 拋出 ArithmeticException

特殊值處理

System.out.println(Math.abs(Double.POSITIVE_INFINITY));  // Infinity
System.out.println(Math.abs(Double.NEGATIVE_INFINITY));  // Infinity
System.out.println(Math.abs(Double.NaN));                // NaN
System.out.println(Math.abs(-0.0));                      // 0.0

實用範例

計算距離

public static int distance(int a, int b) {
    return Math.abs(a - b);
}

System.out.println(distance(10, 3));   // 7
System.out.println(distance(3, 10));   // 7
System.out.println(distance(-5, 5));   // 10

判斷數值相近

public static boolean isClose(double a, double b, double tolerance) {
    return Math.abs(a - b) <= tolerance;
}

System.out.println(isClose(0.1 + 0.2, 0.3, 0.0001));  // true

重點整理

  • Math.abs() 回傳數值的絕對值
  • 支援 intlongfloatdouble
  • 注意 Integer.MIN_VALUE 的溢位問題
  • Java 15+ 可用 Math.absExact() 進行安全計算