数字处理工具类
-
BigInteger:可以让超过Integer范围内的数据进行运算
构造方法:public BigInteger(String val)
常用方法:
public BigInteger add(BigInteger val)
public BigInteger subtract(BigInteger val)
public BigInteger multiply(BigInteger val)
public BigInteger divide(BigInteger val)
public BigInteger remainder(BigInteger val)
public BigInteger[] divideAndRemainder(BigInteger val)
package com.lili.MathUntil;
import java.math.BigInteger;
import java.util.Arrays;
/**
* 数字处理工具类:
* @author: QiJingJing
* @create: 2021/7/7
*/
public class Test1 {
public static void main(String[] args){
String s1 = "934374337463746372323";
String s2 = "343434343434345454454";
BigInteger i1 = new BigInteger(s1);
BigInteger i2 = new BigInteger(s2);
System.out.println(i1.add(i2));// + 1277808680898091826777
System.out.println(i1.subtract(i2));// - 590939994029400917869
System.out.println(i1.multiply(i2));// * 320896237108763267933228964625027322676642
System.out.println(i1.divide(i2)); // / 2
System.out.println(i1.remainder(i2));// % 247505650595055463415
System.out.println(Arrays.toString(i1.divideAndRemainder(i2)));// /and%[2, 247505650595055463415]
}
}
-
BigDecimal: 由于在运算的时候,float和double很容易精度丢失,java提供了BigDecimal
构造方法:public BigDecimal (String val)
常用方法:
public BigDecimal add(BigDecimal val)
public BigDecimal subtract(BigDecimal val)
public BigDecimal multiply(BigDecimal val)
public BigDecimal divide(BigDecimal val)
package com.lili.MathUntil;
import java.math.BigDecimal;
import java.math.BigInteger;
/**
* 数字处理工具类
* BigDecimal
* BigDecimal: 由于在运算的时候,float和double很容易精度丢失,java提供了BigDecimal
* 构造方法:public BigDecimal (String val)
* 常用方法:
* public BigDecimal add(BigDecimal val)
* public BigDecimal subtract(BigDecimal val)
* public BigDecimal multiply(BigDecimal val)
* public BigDecimal divide(BigDecimal val)
*
* @author: QiJingJing
* @create: 2021/7/7
*/
public class Test2 {
public static void main(String[] args) {
String s1 = "93437433746.3746372324";
String s2 = "4";
BigDecimal i1 = new BigDecimal(s1);
BigDecimal i2 = new BigDecimal(s2);
System.out.println(i1.add(i2));// + 93437433750.3746372324
System.out.println(i1.subtract(i2));// - 93437433742.3746372324
System.out.println(i1.multiply(i2));// * 373749734985.4985489296
System.out.println(i1.divide(i2)); // / 23359358436.5936593081
}
}
-
DecimalFomat: java提供的类,帮你用最快的速度将数字格式格式化你想要的样子
示例:
package com.lili.MathUntil; import java.text.DecimalFormat; /** * DecimalFormat: java提供的类,帮你用最快的速度将数字格式格式化你想要的样子 * * @author: QiJingJing * @create: 2021/7/7 */ public class Test3 { public static void main(String[] args) { double b = 23.26778536; // 取两位整数 System.out.println(new DecimalFormat("00").format(b));//23 // 取两位整数和两位小数 System.out.println(new DecimalFormat("00.00").format(b));//23.27 // 取三位整数数和三位小数,整数不足部分以0替补 System.out.println(new DecimalFormat("000.000").format(b));//023.268 // 取所有整数部分 System.out.println(new DecimalFormat("#").format(b));//23 // 以百分比形式计算,并取两位小数 System.out.println(new DecimalFormat("#.##%").format(b));//2326.78% } }