package cn.liuliu.com; import java.math.BigDecimal; import java.math.BigInteger; /* * 一、Math类? * * 1.是数学工具类,可以做一些数学计算。---->开方 对数 三角函数等! * 2.所有的方法都是 静态方法, 不需要new ,直接调用类名即可! * * 二、BigInteger类?----->大数运算! * * 当数字超过了 long的范围 计算时用BigInteger! * * 1.定义大数,通过new的方式! 【计算的数字需要加上引号!】 2.计算值 a1.add(a2);两数相加! * BigInteger a1=new BigInteger("454654654646464646464564"); BigInteger a2=new BigInteger("46546489798798798798787498"); BigInteger a3=a1.add(a2); //a1+a2; * * 三、BigDecimal类?------>浮点大数运算,提高浮点数运算精度! * * 计算机 二进制 表示浮点数会不精确! 解决方法 BigDecimal! * * 1.定义小数,通过new的方式!【计算的数字需要加上引号!】 2.计算值 a1.add(a2);两数相加! * BigDecimal a1=new BigDecimal("0.09"); BigDecimal a2=new BigDecimal("0.01"); BigDecimal a3=a1.add(a2); //a1+a2; */ public class MathDemo { public static void main(String[] args) { math(); pow$and$sqrt(); random(); bigIntegerDemo(); bigDecimal(); } //1.绝对值 public static void math(){ int i=Math.abs(-10); System.out.print(i+" "); //10 System.out.println(); double i01=Math.floor(7.9); //向下舍入 7 double i02=Math.ceil(8.1); //向上舍入 9 double i03=Math.round(1.4); //四舍五入规则! System.out.println(i01+" "+i02+" "+i03); } //2.求 次方 和 开平方! public static void pow$and$sqrt(){ double a=Math.pow(4, 4); //4的4次方。前面是数,后面是需要求的次方数!double定义! double a1=Math.sqrt(16); //16开平方 4 System.out.print(a+" "); System.out.println(a1); } //3.创建一个随机数 0---1之间! public static void random(){ double a= Math.random(); //默认定义double 定义int 需要强制转型! System.out.println(a); } //4.大数运算! public static void bigIntegerDemo(){ BigInteger a1=new BigInteger("454654654646464646464564"); BigInteger a2=new BigInteger("46546489798798798798787498"); BigInteger a3=a1.add(a2); //a1+a2; System.out.println("大数运算结果 "+a3); } //5.浮点大数运算! public static void bigDecimal(){ System.out.println(0.09+0.01); //计算机 二进制 表示浮点数会不精确! 解决方法 BigDecimal! BigDecimal a1=new BigDecimal("0.09"); BigDecimal a2=new BigDecimal("0.013"); BigDecimal a3=a1.add(a2); BigDecimal a4=a1.divide(a2,3,BigDecimal.ROUND_HALF_UP); //不能整除 出现异常!数字【3】就是保留三位小数 【 BigDecimal.ROUND_HALF_UP】四舍五入! System.out.println(a3); System.out.println(a4); } }
原文:https://www.cnblogs.com/ZXF6/p/10582753.html