一、Math类
Math是一个数学操作类,在Math类之中提供有大量的数学操作方法。但是在这个类里面只强调一个round()方法:public static long round(double a)。
范例:使用四舍五入
public class TestDemo { public static void main(String[] args) throws Exception { System.out.println(Math.round(19.5)); } }
扩展题目:请说出“Math.round(13.5)”、“Math.round(-13.5)”、“Math.round(-13.51)”结果是什么?
- Math.round(13.5):14;
- Math.round(-13.5):-13;
- Math.round(-13.51):-14。
二、Random类
java.util.Random类的主要功能是用于产生随机数。
范例:观察代码
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(100) + "、"); } } }
这一个类意义不大,有些了解就够了。
三、大数字操作类:BigInteger 、BigDecimal
如果说现在有两个非常大的数字(超过了double范围)要进行数学的加法计算,你该怎么做?可以使用字符串保存数字,而后按照每个字符进行手工的处理数学计算。但是这样的复杂度非常的高,为此,在Java里面专门提供了一个java.math包,此包之中提供有两个大数字操作类:BigInteger(大整数操作类)、BigDecimal(大小数操作类)。
1、 大整数操作类:BigInteger
BigInteger是Number的子类,但是在使用的时候肯定不用转为Number类型,在BigInteger类之中定义的构造方法:public BigInteger(String val),因为数据量一大,肯定使用String表示;
范例:完成四则运算
import java.math.BigInteger; public class TestDemo { public static void main(String[] args) throws Exception { BigInteger bigA = new BigInteger("4238903289023809238097890"); BigInteger bigB = new BigInteger("98234789234"); 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]); System.out.println(bigA.pow(Integer.MAX_VALUE)); } }
以上只是针对于BigInteger类做了一个演示,但是这样的代码意义不大,而且也没使用的环境,如果你在工作之中,如果真遇见了数学问题,一定要去找数学公式第三方开发包。
2、大小操作类:BigDecimal
此类的操作与BigInteger类基本是相同的,也提供有基本的数学计算,但是与这些数学计算相比,BigDecimal类有一个非常重要的功能。
Math类之中的round()方法进行四舍五入操作过程之中,采用的是所有小数点全部进位,不能保留小数位,但是很多时候这样的做法是不可取,例如:如果某家公司的年收入是按照亿计算,今年收获了5.321亿美金,按照Math.round()结果就成了5亿,所以Math.round()是一个不可能使用的操作,这个时候只能够利用BigDecimal类完成。
在BigDecimal类里面提供有一个除法操作:public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode)
- 第一个参数:被除数,此处也应该是BigDecimal类型;
- 第二个参数:保留的小数位数;
- 第三个参数:进位模式(public static final int ROUND_HALF_UP)。
范例:实现准确的四舍五入操作
import java.math.BigDecimal; class MyMath { public static double round(double num, int scale) { BigDecimal bigNum = new BigDecimal(num); // 只有变为BigDecimal才可以调用divide()方法 BigDecimal result = bigNum.divide(new BigDecimal(1), scale, BigDecimal.ROUND_HALF_UP); return result.doubleValue(); } } public class TestDemo { public static void main(String[] args) throws Exception { System.out.println(MyMath.round(7809.652198, 2)); System.out.println(MyMath.round(7809.652198, 1)); System.out.println(MyMath.round(-13.5, 0)); } }
此代码是在工作上使用最多的四舍五入操作模式,如果有需要代码直接使用。