在java开发过程中,为了提高数据的精确性,特别是财务方面的结算,经常采用BigDecimal型数据类型,其引用及精确度情况如下:
package com.yzq.te;
import java.math.BigDecimal;
public class Bigdecimal {
public static double add(double value1,double value2){
BigDecimal b1 = new BigDecimal(Double.valueOf(value1));
BigDecimal b2 = new BigDecimal(Double.valueOf(value2));
return b1.add(b2).doubleValue();
}
public static double subtract(double value1,double value2)
{ BigDecimal b1 = new BigDecimal(Double.valueOf(value1));
BigDecimal b2 = new BigDecimal(Double.valueOf(value2));
return b1.subtract(b2).doubleValue();
}
public static double multiply(double value1,double value2)
{ BigDecimal b1 = new BigDecimal(Double.valueOf(value1));
BigDecimal b2 = new BigDecimal(Double.valueOf(value2));
return b1.multiply(b2).doubleValue();
}
public static double divide(double value1,double value2,int scale){
BigDecimal b1 = new BigDecimal(Double.valueOf(value1));
BigDecimal b2 = new BigDecimal(Double.valueOf(value2));
return b1.divide(b2,scale).doubleValue();
}
public static void main(String[] args) {
System.out.println(Bigdecimal.add(0.1, 0.2));
System.out.println(Bigdecimal.subtract(0.3, 0.1));
System.out.println(Bigdecimal.multiply(0.3, 0.12));
System.out.println(Bigdecimal.divide(0.3, 0.13,1));
}
}
运行结果为:
0.30000000000000004
0.19999999999999998
0.036 2.3076923076923075