JavaApp_高精度计算

2017-09-13 10:41:10来源:oschina作者:Craft_007人点击

分享
package com.family.PreciseCompute;
import java.math.BigDecimal;
import java.math.BigInteger;
public class PrecisionCompute {
/**
* @desc 使用BigInteger 和 BigDecimal进行高精度计算
* */
public static void main(String[] args) {
add();
subtract();
divide();
multiply();
pow();
}
public static void add () {
BigInteger a = new BigInteger("3232323");
BigInteger b = new BigInteger("323243554545");
BigDecimal c = new BigDecimal(234.5454);
BigDecimal d = new BigDecimal(456.0001);

System.out.println("a+b="+a.add(b));
System.out.println("c+d="+c.add(d).setScale(4, 4));
}
public static void subtract(){
BigInteger a = new BigInteger("3232323");
BigInteger b = new BigInteger("323243554545");
BigDecimal c = new BigDecimal(234.5454);
BigDecimal d = new BigDecimal(456.0001);

System.out.println("a-b="+a.subtract(b));
System.out.println("c-d="+c.subtract(d).setScale(4, 4));
}
public static void divide(){
BigInteger a = new BigInteger("100000000000000");
BigInteger b = new BigInteger("5");
BigDecimal c = new BigDecimal(120.22);
BigDecimal d = new BigDecimal(2.0);

System.out.println("a/b="+a.divide(b));
System.out.println("c/d="+c.subtract(d).setScale(4, 4));
}
public static void multiply () {
BigInteger a = new BigInteger("100000000000000");
BigInteger b = new BigInteger("5");
BigDecimal c = new BigDecimal(120.22);
BigDecimal d = new BigDecimal(2.0);

System.out.println("a*b="+a.multiply(b));
System.out.println("c*d="+c.multiply(d).setScale(4, 4));
}
public static void pow () {
BigInteger a = new BigInteger("100000000000000");
BigInteger b = new BigInteger("5");
BigDecimal c = new BigDecimal(120.22);
BigDecimal d = new BigDecimal(2.0);

System.out.println("a%b="+a.pow(b.intValue()));
System.out.println("c%d="+c.pow(d.intValue()).setScale(4, 4));
}

//此外,BigDecimal以及BigInteger还有很多API,具体参考JAVA API
}

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台