测试
package cn.edut.tarena.demo1;
import java.math.BigDecimal;
public class Test7_BigDEcimal {
public static void main(String[] args) {
double f1 = 10.5 ;
double f2 = 3.1;
System.out.println("------------------double类型运算:");
System.out.println("f1="+f1 + ",f2="+f2);
System.out.println(f1+"+"+f2+"="+(f1+f2));
System.out.println(f1+"-"+f2+"="+ (f1-f2));
System.out.println(f1+"*"+f2+"="+f1*f2);
System.out.println(f1+"/"+f2+"="+f1/f2);
System.out.println();
BigDecimal b1 = new BigDecimal(f1);
BigDecimal b2 = new BigDecimal(f2);
System.out.println("------------------BigDecimal工具运算:");
System.out.println("f1="+b1.doubleValue() + ",f2="+b2.doubleValue());
System.out.println(f1+"+"+f2+"="+b1.add(b2).floatValue());
System.out.println(f1+"-"+f2+"="+ b1.subtract(b2).floatValue());
System.out.println(f1+"*"+f2+"="+b1.multiply(b2).floatValue());
try {
System.out.println(f1+"/"+f2+"="+b1.divide(b2).floatValue());
System.out.println("除不尽,我就不会出来!!");
}catch (Exception e) {
System.out.println(f1+"/"+f2+"="+b1.divide(b2,3,BigDecimal.ROUND_HALF_UP).floatValue());
}
}
}
结果