Java Number & Math 类详解

在Java中,Number类和Math类是两个非常重要的类,分别用于处理数字和数学运算。以下是对这两个类的详细解释。

1. Number 类

Number是一个抽象类,位于java.lang包中。它是所有数字类的父类,包括IntegerDoubleFloatLongShortByte等。Number类提供了一些方法,用于将数字转换为不同的基本数据类型。

主要方法

  • intValue(): 返回数字的int值。
  • longValue(): 返回数字的long值。
  • floatValue(): 返回数字的float值。
  • doubleValue(): 返回数字的double值。

示例

public class NumberExample {
   
    public static void main(String[] args) {
   
        Integer intValue = 100;
        Double doubleValue = 100.5;

        System.out.println("Integer as int: " + intValue.intValue());
        System.out.println("Double as double: " + doubleValue.doubleValue());
    }
}
 
 

2. Math 类

Math类是一个最终类,位于java.lang包中,提供了许多静态方法用于执行基本的数学运算。该类不需要实例化,可以直接通过类名调用其方法。

主要方法

  • abs(): 返回绝对值。
  • max(): 返回两个值中的最大值。
  • min(): 返回两个值中的最小值。
  • pow(): 返回第一个参数的第二个参数次方。
  • sqrt(): 返回平方根。
  • random(): 返回一个0.0到1.0之间的随机数。
  • round(): 返回四舍五入后的值。

示例

public class MathExample {
   
    public static void main(String[] args) {
   
        double a = -5.5;
        double b = 3.0;

        System.out.println("Absolute value of a: " + Math.abs(a));
        System.out.println("Max value: " + Math.max(a, b));
        System.out.println("Min value: " + Math.min(a, b));
        System.out.println("Power: " + Math.pow(2, 3)); // 2的3次方
        System.out.println("Square root of 16: " + Math.sqrt(16));
        System.out.println("Random number: " + Math.random());
        System.out.println("Rounded value of 5.7: " + Math.round(5.7));
    }
}

3. NumberFormat 类

除了NumberMath类,Java还提供了NumberFormat类,用于格式化数字。它可以用于将数字格式化为货币、百分比等。

示例

import java.text.NumberFormat;

public class NumberFormatExample {
   
    public static void main(String[] args) {
   
        double number = 1234567.89;

        NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
        System.out.println("Currency format: " + currencyFormat.format(number));

        NumberFormat percentFormat = NumberFormat.getPercentInstance();
        System.out.println("Percent format: " + percentFormat.format(0.75));
    }
}

总结

  • Number类是所有数字类的父类,提供了将数字转换为不同基本数据类型的方法。
  • Math类提供了多种静态方法用于执行数学运算,如绝对值、最大值、最小值、幂运算等。
  • NumberFormat类用于格式化数字,适用于货币和百分比等场景。

这两个类在Java编程中非常常用,掌握它们的用法可以帮助你更好地处理数字和数学运算。

posted @ 2025-07-03 15:43  晃悠人生  阅读(15)  评论(0)    收藏  举报