Java Number Math 类
Java Number Math 类学习笔记详细版在 Java 中Number是数值类型的抽象基类而Math类提供了丰富的数学运算工具。掌握这两个类对于处理数值计算、格式化输出和科学运算至关重要。一、Number 类 (数值包装类)1. 概述位置java.lang.Number性质抽象类Abstract Class不能直接实例化。作用它是所有数值包装类的父类提供了将数值转换为基本数据类型的方法。继承体系java.lang.Number ├── Byte ├── Short ├── Integer ├── Long ├── Float ├── Double └── BigInteger (java.math, 非 Number 子类但类似) └── BigDecimal (java.math, 非 Number 子类但类似)2. 核心方法Number类定义了以下抽象方法所有子类必须实现用于将包装对象转换为对应的基本类型方法描述返回值类型intValue()转换为intintlongValue()转换为longlongfloatValue()转换为floatfloatdoubleValue()转换为doubledoublebyteValue()转换为bytebyteshortValue()转换为shortshort注意如果转换导致精度丢失如double转int小数部分会被截断不会四舍五入。3. 代码示例IntegernumInt100;DoublenumDouble100.99;// 转换为 intinti1numInt.intValue();// 100inti2numDouble.intValue();// 100 (小数部分被截断)// 转换为 doubledoubled1numInt.doubleValue();// 100.0doubled2numDouble.doubleValue();// 100.99// 自动拆箱 (Auto-unboxing)// Java 5 允许直接将包装类赋值给基本类型编译器会自动调用 xxxValue()inti3numInt;doubled3numDouble;4. 自动装箱与拆箱 (Auto-boxing/Unboxing)装箱基本类型 → 包装类 (int→Integer)拆箱包装类 → 基本类型 (Integer→int)场景集合ListInteger只能存储对象不能存储基本类型因此必须装箱。ListIntegerlistnewArrayList();list.add(10);// 自动装箱int 10 - Integer(10)intvallist.get(0);// 自动拆箱Integer(10) - int 10二、Math 类 (数学工具类)1. 概述位置java.lang.Math性质最终类 (final)不能被继承。所有方法都是static的无需实例化直接通过Math.方法名()调用。构造函数是private的防止实例化。常量Math.PI圆周率π\piπ(3.14159…)Math.E自然对数底eee(2.71828…)2. 常用方法详解A. 绝对值、最大值、最小值方法描述示例abs(a)返回绝对值Math.abs(-5)→5max(a, b)返回较大值Math.max(10, 20)→20min(a, b)返回较小值Math.min(10, 20)→10B. 幂运算与开方方法描述示例pow(a, b)返回aba^babMath.pow(2, 3)→8.0sqrt(a)返回平方根Math.sqrt(16)→4.0cbrt(a)返回立方根Math.cbrt(27)→3.0C. 取整与舍入方法描述示例ceil(a)向上取整 (天花板)Math.ceil(3.1)→4.0floor(a)向下取整 (地板)Math.floor(3.9)→3.0round(a)四舍五入(返回int或long)Math.round(3.5)→4rint(a)四舍五入到最接近的整数 (返回double)Math.rint(3.5)→4.0注意Math.round()的规则是floor(a 0.5)。3.5→4-3.5→-3(因为-3.5 0.5 -3.0,floor(-3.0) -3)D. 随机数方法描述示例random()返回[0.0, 1.0)之间的doubleMath.random()生成指定范围的随机整数// 生成 [min, max] 之间的随机整数intrandomNum(int)(Math.random()*(max-min1))min;// 示例生成 1 到 100 的随机数intnum(int)(Math.random()*100)1;E. 三角函数与对数方法描述参数单位sin(a),cos(a),tan(a)三角函数弧度(Radian)asin(a),acos(a),atan(a)反三角函数返回弧度log(a)自然对数 (lna\ln alna)-log10(a)以 10 为底的对数-toRadians(deg)角度转弧度-toDegrees(rad)弧度转角度-角度与弧度转换示例doubleangleDeg90;doubleangleRadMath.toRadians(angleDeg);// 1.5707...doublesinValMath.sin(angleRad);// 1.0三、进阶精确计算 (BigDecimal)重要警告double和float是二进制浮点数无法精确表示某些十进制小数如 0.1导致计算误差。System.out.println(0.10.2);// 输出0.30000000000000004 (错误)解决方案使用java.math.BigDecimal类进行精确计算常用于金融、货币。1. 创建 BigDecimal推荐使用String构造函数避免double构造时的精度问题。// ✅ 推荐BigDecimalanewBigDecimal(0.1);BigDecimalbnewBigDecimal(0.2);// ❌ 不推荐 (会有精度问题)BigDecimalcnewBigDecimal(0.1);2. 常用运算BigDecimal是不可变的运算后必须接收返回值。方法描述示例add(b)加法a.add(b)subtract(b)减法a.subtract(b)multiply(b)乘法a.multiply(b)divide(b, scale, roundingMode)除法 (需指定精度和舍入模式)a.divide(b, 2, RoundingMode.HALF_UP)代码示例importjava.math.BigDecimal;importjava.math.RoundingMode;publicclassPreciseCalc{publicstaticvoidmain(String[]args){BigDecimalpricenewBigDecimal(19.99);BigDecimaltaxnewBigDecimal(0.08);// 8% 税// 计算税额BigDecimaltaxAmountprice.multiply(tax);// 除法示例 (保留 2 位小数四舍五入)BigDecimaltotalprice.add(taxAmount);BigDecimalunitPricetotal.divide(newBigDecimal(3),2,RoundingMode.HALF_UP);System.out.println(单价unitPrice);// 输出7.00}}四、NumberFormat 与 DecimalFormat (数字格式化)用于将数字格式化为字符串如货币、百分比、千分位。1. NumberFormat (通用)importjava.text.NumberFormat;importjava.util.Locale;doublenum1234567.89;// 千分位格式化NumberFormatnfNumberFormat.getNumberInstance(Locale.CHINA);System.out.println(nf.format(num));// 1,234,567.89// 货币格式化NumberFormatcfNumberFormat.getCurrencyInstance(Locale.CHINA);System.out.println(cf.format(num));// ¥1,234,567.89// 百分比格式化NumberFormatpfNumberFormat.getPercentInstance(Locale.CHINA);System.out.println(pf.format(0.85));// 85%2. DecimalFormat (自定义格式)更灵活使用模式字符串。#数字占位符无数字不显示。0数字占位符无数字补 0。,千分位分隔符。.小数点。importjava.text.DecimalFormat;DecimalFormatdfnewDecimalFormat(###,###.00);System.out.println(df.format(1234.5));// 1,234.50DecimalFormatdf2newDecimalFormat(00000);System.out.println(df2.format(123));// 00123 (补零)五、常见易错点与最佳实践1. 浮点数精度陷阱问题double计算不精确。解决涉及金钱、精确计算时必须使用BigDecimal。比较不要直接用比较double应使用Math.abs(a - b) epsilon。2.Math.random()vsRandom类Math.random()底层使用Random类返回double。java.util.Random功能更强大可生成int,long,boolean,nextGaussian()等且可设置种子用于测试。RandomrandnewRandom();intrrand.nextInt(100);// 0-993. 整数溢出Math类的方法如果结果溢出不会抛出异常而是返回MAX_VALUE或MIN_VALUEJava 8 之前或者抛出ArithmeticExceptionJava 8 的Math.addExact等。建议在关键计算中使用Math.addExact,Math.multiplyExact等带Exact后缀的方法溢出时直接报错。try{intresultMath.addExact(Integer.MAX_VALUE,1);}catch(ArithmeticExceptione){System.out.println(溢出);}4. 角度与弧度Math的三角函数默认使用弧度。如果输入是角度务必先调用Math.toRadians()转换。5.BigDecimal的除法divide()方法如果除不尽如 1/3不指定精度会抛出ArithmeticException。必须指定scale(小数位数) 和RoundingMode(舍入模式)。六、总结速查表类名核心用途关键方法/特性Number数值包装类的父类intValue(),doubleValue(), 自动拆箱Math数学运算工具abs,max,min,pow,sqrt,random,roundBigDecimal精确数值计算add,subtract,multiply,divide(需指定精度)DecimalFormat数字格式化模式字符串 (#,##0.00)核心原则一般计算使用Math类简单高效。金融计算必须使用BigDecimal避免精度丢失。格式化输出使用NumberFormat或DecimalFormat。随机数简单用Math.random()复杂用Random类。掌握这些类你就能轻松应对 Java 中绝大多数的数值处理需求