[TOC]

一. Math类 (了解)

    Math就是一个专门进行数学计算的操作类,里面提供了一系列的数学计算方法。(数学开发则不够用,需要学习一个组件包)
    在Math类里面提供的一切方法都是static型的方法,因为Math类里面没有普通属性。
    在整个Math类里面实际上只有一个方法能够引起我们的注意:

  • 四舍五入: public static long round(double a)

范例: 观察四舍五入

1
2
3
4
5
6
7
8
    package cn.ngp.demo;
public class TestDemo {
public static void main(String[] args) throws Exception {
System.out.println(Math.round(15.5)); //16
System.out.println(Math.round(-15.5)); //-15
System.out.println(Math.round(-15.51)); //-16
}
}

二. Random类

1
2
3
4
5
6
7
8
9
10
package cn.ngp.demo;
import java.util.Random;
public class TestDemo {
public static void main(String[] args) throws Exception {
Random rand = new Random();
for(int x = 0 ; x < 10 ; x ++) {
System.out.print(rand.nextInt(10)+"、"); //生成小于10的随机数
}
}
}

三. BigInteger

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package cn.ngp.demo;
import java.math.BigInteger;
public class TestDemo {
public static void main(String[] args) {
BigInteger bigA = new BigInteger("11111111111111");
BigInteger bigB = new BigInteger("2222222222");
System.out.println("加法:" + bigA.add(bigB));
System.out.println("减法:" + bigA.subtract(bigB));
System.out.println("乘法:" + bigA.multiply(bigB));
System.out.println("除法:" + bigA.divide(bigB));
//数组里面只有两个元素: 第一个元素表示的是商,第二个元素表示的是余数
BigInteger result[] = bigA.divideAndRemainder(bigB);
System.out.println("商: " + result[0] + " , 余数: " + result[1]);
}
}

    在Java里面虽然提供了大数字的操作类,但是很多时候,我们项目开发可能对数字要求会更加的敏感,而这个时候Java本身所提供的数字类是帮助不大的。这个时候就只能去找第三方的数据开发包来实现了。

四. 大复点数 BigDecimal (重点)

    BigInteger不能够保存小数,而BigDecimal可以保存小数数据。在BigDecimal类里面提供有如下的构造:

  • 构造一: public BigDecimal(String val);
  • 构造二: public BigDecimal(double val);

    与BigInteger一样,BigDecimal本身也支持基础的数学计算。课时使用BigDecimal还有一个非常重要的目的: 就是可以利用它来实现准确的四舍五入操作。
    之前使用过Math.round()实现过四舍五入操作,但是这个操作有一个问题,所有的小数都四舍五入了。那么假设一家公司的年收入按照亿进行计算,今年收入: 3.45678亿,按照Math.round()就少了4567.8万。

  • 除法操作: public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode)
    • BigDecimal divisor : 被除数;
    • int scale : 保留的小数位;
    • int roundingMode : 进位模式 (public static final int ROUND_HALF_UP)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package cn.ngp.demo;
import java.math.BigDecimal;
class MyMath{
/**
* 实现准确的四舍五入操作
* @param num 要进行四舍五入操作的数字
* @param scale 要保存的小数位
* @return 处理后的四舍五入数据
*/
public static double round(double num,int scale) {
BigDecimal bigA = new BigDecimal(num);
BigDecimal bigB = new BigDecimal(1);
return bigA.divide(bigB,scale,BigDecimal.ROUND_HALF_UP).doubleValue();
}
}
public class TestDemo {
public static void main(String[] args) {
System.out.println(MyMath.round(15.5, 0));
System.out.println(MyMath.round(-15.51, 0));
System.out.println(MyMath.round(-15.5, 0));
System.out.println(MyMath.round(4.5678, 2));
}
}

    此类操作的功能在日后的开发之中一定要会使用,属于工具类的支持范畴。
总结:

  1. Math类重点要清楚round()方法的坑;
  2. Random类生成随机数;
  3. 如果数据量大就使用BigInteger或BigDecimal,这两个类是Number的子类。

参考

来自: 阿里云大学(笔记) → 零基础学Java10系列三:Java高级编程