蓝色天空.知识 · 实践 · 创造
我的收藏
Java 教程目录 57章
Java / LEARN BY DOING

Java Number & Math 类

梳理 Java 数值包装类继承体系、Number 抽象转换方法、自动装箱拆箱、BigInteger/BigDecimal 与 NumberFormat,并全面实测 Math 类的三角、指数对数、随机数及 floor/round/ceil 取整差异。

学完这一章,你能够

  • 梳理 Java 数值包装类继承体系、Number 抽象转换方法、自动装箱拆箱、BigInteger/BigDecimal 与 NumberFormat,并全面实测 Math 类的三角、指数对数、随机数及 floor/round/ceil 取整差异。

Number 包装类与自动装箱拆箱

日常数值计算通常直接使用 `byte`、`short`、`int`、`long`、`float`、`double` 等基本数据类型(如 `int a = 5000; float b = 13.65f; byte c = 0x4a;`)。但在集合泛型、反射或需要对象引用的场景中,Java 在 `java.lang` 包中提供了对应包装类,所有数值包装类以及大数类均继承自抽象类 `Number`。从 Java 5 起编译器支持自动装箱(如 `Integer autoBoxed = 42` 编译为 `Integer.valueOf(42)`)与自动拆箱(如 `int autoUnboxed = autoBoxed` 编译为 `autoBoxed.intValue()`)。

`Number` 抽象类实现了 `Serializable`,声明了 `intValue()`、`longValue()`、`floatValue()`、`doubleValue()` 四个抽象方法以及默认实现的 `byteValue()` 与 `shortValue()`。例如执行 `Integer x = 5; x = x + 10;` 时,先将字面量 `5` 装箱为 `Integer`,参与加法时拆箱为 `int`,相加后再重新装箱得到 `15`。本地 OpenJDK 1.8.0_492 实测同时核验了 `Integer.parseInt("256")`、`Integer.valueOf("128")`、`compareTo` 与 `equals`。

Number 类型转换、比较、大数与格式化

借助 `Number` 的多态视图,可将 `Number num = 1234.56` 统一转换为不同基本类型:`intValue()` 与 `longValue()` 会直接截断小数返回 `1234`,`floatValue()` 与 `doubleValue()` 保留小数 `1234.56`,`byteValue()` 按低 8 位截断返回 `-46`。比较不同包装类数值(如 `Integer(10)` 与 `Double(10.0)`)时,不可直接调用 `equals`(跨类型返回 `false`),应统一转为同类型后比较 `x.doubleValue() == y.doubleValue()` 得到 `true`。

超出 64 位整数或需要精确十进制小数运算时,应选用 `java.math.BigInteger` 与 `java.math.BigDecimal`。本地实测 `BigInteger("12345678901234567890").add(1)` 精确得到 `12345678901234567891`,`BigDecimal("1234567890.1234567890").multiply(2)` 得到 `2469135780.2469135780`;配合 `NumberFormat.getInstance(Locale.US)` 设置 `setMaximumFractionDigits(2)` 将 `1234.5678` 格式化为 `1,234.57`。

Math 静态数学方法与常量

`java.lang.Math` 提供全静态数学方法与 `Math.PI`(约 `3.141592653589793`)、`Math.E`(约 `2.718281828459045`)常量,覆盖三角函数、反三角函数及角度弧度换算。实测 `Math.sin(Math.PI/2)` 与 `Math.cos(0)` 均为 `1.0`、`Math.tan(Math.PI/3)` 约 `1.7321`、`Math.atan(1)` 约 `0.7854`、`Math.toDegrees(Math.PI/2)` 为 `90.0`、`Math.toRadians(180.0)` 约 `3.1416`。

高级运算方面,`Math.exp(1)` 约 `2.7183`,`Math.log(Math.E)` 为 `1.0`,`Math.log10(100)` 为 `2.0`;`Math.hypot(3, 4)` 避免中间溢出直接算出斜边 `5.0`,`Math.IEEEremainder(10, 3)` 按 IEEE 754 规则返回 `1.0`;`Math.random()` 返回 `[0.0, 1.0)` 区间伪随机双精度浮点数,缩放 `(int)(Math.random() * 100) + 1` 可稳定落在 `[1, 100]` 区间(本地 20 次采样全部命中)。

Math.floor、Math.round 与 Math.ceil 对比

三种取整函数在正数与负数边界上差异显著:`Math.floor(x)` 向下取整返回 `<= x` 的最大整数(`double`),`Math.ceil(x)` 向上取整返回 `>= x` 的最小整数(`double`),而 `Math.round(x)` 等价于 `Math.floor(x + 0.5)` 并返回 `long`(`float` 重载返回 `int`)。因此对负半数 `-1.5` 与 `-11.5`,`Math.round(-1.5)` 为 `-1`、`Math.round(-11.5)` 为 `-11`,并非向零或远离零对称舍入;全部 6 组正负样例已在本地实测核对。

Java 数值包装类与高精度数值类对照

类名对应基本类型说明
Bytebyte8 位有符号字节型包装类
Shortshort16 位短整型包装类
Integerint32 位整型包装类
Longlong64 位长整型包装类
Floatfloat32 位单精度浮点包装类
Doubledouble64 位双精度浮点包装类
BigInteger-java.math 不可变任意精度整数
BigDecimal-java.math 不可变任意精度十进制小数

Number 与 Math 常用方法参考

序号方法与核心说明
1`xxxValue()`:将 `Number` 对象转换为对应的 `byte/short/int/long/float/double` 基本类型值
2`compareTo()`:将当前包装类数值与同类型参数按大小比较,返回负/零/正整数
3`equals()`:判断当前包装类对象与参数类型及数值是否完全相等
4`valueOf()`:按基本值或字符串返回对应包装类对象(如 `Integer.valueOf`)
5`toString()`:将数值转换为十进制字符串表示
6`parseInt()`:静态解析数字字符串为基本 `int` 值
7`Math.abs()`:返回整数或浮点参数的绝对值
8`Math.ceil()`:返回大于等于参数的最小整数值(返回 `double`)
9`Math.floor()`:返回小于等于参数的最大整数值(返回 `double`)
10`Math.rint()`:返回最接近参数的整数(`double`),居中时向偶数舍入(如 `rint(2.5) == 2.0`)
11`Math.round()`:按 `floor(x + 0.5)` 规则取整,实测 `round(11.5)=12`、`round(-11.5)=-11`
12`Math.min()`:返回两个同型数值中的较小值
13`Math.max()`:返回两个同型数值中的较大值
14`Math.exp()`:计算自然常数 `e` 的指定次幂
15`Math.log()`:计算以 `e` 为底的自然对数
16`Math.pow()`:计算第一个参数的第二个参数次幂
17`Math.sqrt()`:计算非负数的算术平方根
18`Math.sin()`:计算弧度参数的正弦值
19`Math.cos()`:计算弧度参数的余弦值
20`Math.tan()`:计算弧度参数的正切值
21`Math.asin()`:计算反正弦值(弧度)
22`Math.acos()`:计算反余弦值(弧度)
23`Math.atan()`:计算反正切值(弧度)
24`Math.atan2()`:根据笛卡尔坐标 `(y, x)` 返回极坐标方位角(弧度)
25`Math.toDegrees()`:将弧度值转换为角度值
26`Math.toRadians()`:将角度值转换为弧度值
27`Math.random()`:返回 `[0.0, 1.0)` 区间内的伪随机 `double` 值

Math.floor、Math.round 与 Math.ceil 实测值对照

参数Math.floorMath.roundMath.ceil
1.41.012.0
1.51.022.0
1.61.022.0
-1.4-2.0-1-1.0
-1.5-2.0-1-1.0
-1.6-2.0-2-1.0

在 OpenJDK 8 实测 Number 装箱转换、BigDecimal/NumberFormat 与 Math 全套运算

含完整源码 · 145 行
展开查看收起
java
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class ExploreNumber {
    private static String esc(String s) {
        StringBuilder sb = new StringBuilder("\"");
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            switch (c) {
                case '\\': sb.append("\\\\"); break;
                case '"': sb.append("\\\""); break;
                case '\n': sb.append("\\n"); break;
                case '\r': sb.append("\\r"); break;
                case '\t': sb.append("\\t"); break;
                default:
                    if (c < 0x20) {
                        sb.append(String.format("\\u%04x", (int) c));
                    } else {
                        sb.append(c);
                    }
            }
        }
        sb.append("\"");
        return sb.toString();
    }

    private static String makeCase(String name, String summary, String expectedJson, String actualJson, boolean passed) {
        return "{\"name\":" + esc(name)
            + ",\"summary\":" + esc(summary)
            + ",\"expected\":" + expectedJson
            + ",\"actual\":" + actualJson
            + ",\"passed\":" + passed + "}";
    }

    public static void main(String[] args) {
        List<String> cases = new ArrayList<String>();

        // 1. Primitive & autoboxing / unboxing / wrapper methods
        int a = 5000;
        float b = 13.65f;
        byte c = 0x4a;
        Integer x = 5;
        x = x + 10;
        Integer autoBoxed = 42;
        int autoUnboxed = autoBoxed;
        int parsed = Integer.parseInt("256");
        Integer valOf = Integer.valueOf("128");
        int cmp = x.compareTo(20);
        boolean eq = x.equals(Integer.valueOf(15));
        String a1 = a + "|" + b + "|" + c + "|" + x + "|" + autoUnboxed + "|" + parsed + "|" + valOf.toString() + "|" + (cmp < 0) + "|" + eq;
        String e1 = "5000|13.65|74|15|42|256|128|true|true";
        cases.add(makeCase("primitive_and_autoboxing", "内置数值类型、自动装箱拆箱与包装类 valueOf/parseInt/toString/compareTo/equals", esc(e1), esc(a1), e1.equals(a1)));

        // 2. Number conversions & cross-type comparison
        Number num = 1234.56;
        Integer ix = 10;
        Double dy = 10.0;
        boolean sameDouble = ix.doubleValue() == dy.doubleValue();
        Byte by = Byte.valueOf((byte) 12);
        Short sh = Short.valueOf((short) 320);
        Long lo = Long.valueOf(9999999999L);
        Float fl = Float.valueOf(2.5f);
        String a2 = num.intValue() + "|" + num.longValue() + "|" + num.floatValue() + "|" + num.doubleValue()
            + "|" + num.byteValue() + "|" + num.shortValue() + "|" + sameDouble
            + "|" + by.byteValue() + "|" + sh.shortValue() + "|" + lo.longValue() + "|" + fl.floatValue();
        String e2 = "1234|1234|1234.56|1234.56|-46|1234|true|12|320|9999999999|2.5";
        cases.add(makeCase("number_conversions_and_compare", "Number 抽象类 xxxValue() 类型转换与统一转 double 比较", esc(e2), esc(a2), e2.equals(a2)));

        // 3. BigInteger, BigDecimal & NumberFormat
        BigInteger bigInt = new BigInteger("12345678901234567890");
        BigInteger sum = bigInt.add(new BigInteger("1"));
        BigDecimal bigDec = new BigDecimal("1234567890.1234567890");
        BigDecimal product = bigDec.multiply(new BigDecimal("2"));
        NumberFormat nf = NumberFormat.getInstance(Locale.US);
        nf.setMaximumFractionDigits(2);
        String formatted = nf.format(1234.5678);
        String a3 = sum.toString() + "|" + product.toPlainString() + "|" + formatted;
        String e3 = "12345678901234567891|2469135780.2469135780|1,234.57";
        cases.add(makeCase("big_numbers_and_format", "BigInteger/BigDecimal 任意精度运算与 NumberFormat 格式化", esc(e3), esc(a3), e3.equals(a3)));

        // 4. Math trig, angle conversion & constants
        String a4 = String.format(Locale.US, "%.4f|%.4f|%.4f|%.4f|%.4f|%.4f|%.4f|%.1f|%.4f|%.6f|%.6f",
            Math.sin(Math.PI / 2),
            Math.cos(0),
            Math.tan(Math.PI / 3),
            Math.atan(1),
            Math.asin(1.0),
            Math.acos(1.0),
            Math.atan2(1.0, 1.0),
            Math.toDegrees(Math.PI / 2),
            Math.toRadians(180.0),
            Math.PI,
            Math.E);
        String e4 = "1.0000|1.0000|1.7321|0.7854|1.5708|0.0000|0.7854|90.0|3.1416|3.141593|2.718282";
        cases.add(makeCase("math_trig_and_constants", "Math 三角/反三角函数、角度弧度互转与 PI/E 常量", esc(e4), esc(a4), e4.equals(a4)));

        // 5. Math exp, log, pow, sqrt, abs, min/max, hypot, IEEEremainder, rint & random range
        boolean randOk = true;
        for (int i = 0; i < 20; i++) {
            double r = Math.random();
            int ri = (int) (r * 100) + 1;
            if (!(r >= 0.0 && r < 1.0 && ri >= 1 && ri <= 100)) {
                randOk = false;
            }
        }
        String a5 = String.format(Locale.US, "%.4f|%.1f|%.1f|%.1f|%.1f|%d|%d|%d|%.1f|%.1f|%.1f|%s",
            Math.exp(1), Math.log(Math.E), Math.log10(100),
            Math.pow(2, 10), Math.sqrt(81),
            Math.abs(-42), Math.min(7, 3), Math.max(7, 3),
            Math.hypot(3, 4), Math.IEEEremainder(10, 3), Math.rint(2.5),
            String.valueOf(randOk));
        String e5 = "2.7183|1.0|2.0|1024.0|9.0|42|3|7|5.0|1.0|2.0|true";
        cases.add(makeCase("math_exp_log_random_misc", "Math 指数对数、幂根、绝对值、极值、hypot/IEEEremainder/rint 与 random 范围", esc(e5), esc(a5), e5.equals(a5)));

        // 6. floor, round, ceil comparison
        double[] nums = {1.4, 1.5, 1.6, -1.4, -1.5, -1.6};
        StringBuilder sb6 = new StringBuilder();
        for (int i = 0; i < nums.length; i++) {
            if (i > 0) sb6.append(";");
            double n = nums[i];
            sb6.append(n).append(":")
               .append(Math.floor(n)).append(",")
               .append(Math.round(n)).append(",")
               .append(Math.ceil(n));
        }
        sb6.append(";half:").append(Math.round(11.5)).append(",").append(Math.round(-11.5));
        String a6 = sb6.toString();
        String e6 = "1.4:1.0,1,2.0;1.5:1.0,2,2.0;1.6:1.0,2,2.0;-1.4:-2.0,-1,-1.0;-1.5:-2.0,-1,-1.0;-1.6:-2.0,-2,-1.0;half:12,-11";
        cases.add(makeCase("math_floor_round_ceil_table", "Math.floor/round/ceil 在正负小数及 ±11.5 边界上的取整对照", esc(e6), esc(a6), e6.equals(a6)));

        StringBuilder out = new StringBuilder();
        out.append("{\"version\":").append(esc(System.getProperty("java.version"))).append(",\"cases\":[");
        for (int i = 0; i < cases.size(); i++) {
            if (i > 0) out.append(",");
            out.append(cases.get(i));
        }
        out.append("]}");
        System.out.println(out.toString());
    }
}
六组用例精准核验装箱拆箱、大数运算、三角对数随机边界以及 floor/round/ceil 六组正负取整结果。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a1139.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:Java

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1139.zip

下载课程关联工程包:Java

课程关联工程包(登记关联57章) · 含当前章节或实例 · mbskycom202612a1104.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

因为 Java 中 Math.round(x) 按 Math.floor(x + 0.5) 计算:-1.5 + 0.5 = -1.0,再向下取整即为 -1。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习