# BigDecimal 精确运算

1、用float或者double变量构建BigDecimal对象。

2、通过调用BigDecimal的加，减，乘，除等相应的方法进行算术运算。

3、把BigDecimal对象转换成float，double，int等类型。

```  BigDecimal b1 = new BigDecimal(Double.toString(0.48));
BigDecimal b2 = BigDecimal.valueOf(0.48);```

```  public BigDecimal add(BigDecimal value);                        //加法
public BigDecimal subtract(BigDecimal value);                   //减法
public BigDecimal multiply(BigDecimal value);                   //乘法
public BigDecimal divide(BigDecimal value);                     //除法```

```
public class Arith {
/**
* @param value1 被加数
* @param value2 加数
* @return 两个参数的和
*/
public static double add(double value1,double value2){
BigDecimal b1 = new BigDecimal(Double.valueOf(value1));
BigDecimal b2 = new BigDecimal(Double.valueOf(value2));
}

/**
* 提供精确减法运算的sub方法
* @param value1 被减数
* @param value2 减数
* @return 两个参数的差
*/
public static double sub(double value1,double value2){
BigDecimal b1 = new BigDecimal(Double.valueOf(value1));
BigDecimal b2 = new BigDecimal(Double.valueOf(value2));
return b1.subtract(b2).doubleValue();
}

/**
* 提供精确乘法运算的mul方法
* @param value1 被乘数
* @param value2 乘数
* @return 两个参数的积
*/
public static double mul(double value1,double value2){
BigDecimal b1 = new BigDecimal(Double.valueOf(value1));
BigDecimal b2 = new BigDecimal(Double.valueOf(value2));
return b1.multiply(b2).doubleValue();
}

/**
* 提供精确的除法运算方法div
* @param value1 被除数
* @param value2 除数
* @param scale 精确范围
* @return 两个参数的商
* @throws IllegalAccessException
*/
public static double div(double value1,double value2,int scale) throws IllegalAccessException{
//如果精确范围小于0，抛出异常信息
if(scale<0){
throw new IllegalAccessException("精确度不能小于0");
}
BigDecimal b1 = new BigDecimal(Double.valueOf(value1));
BigDecimal b2 = new BigDecimal(Double.valueOf(value2));
return b1.divide(b2, scale).doubleValue();
}
}
```

## 4 thoughts on “BigDecimal 精确运算”

1. That kind of thkiinng shows you’re an expert

2. I just wanted to compose a quick message so as to express gratitude to you for all of the wonderful strategies you are placing on this site. My time-consuming internet lookup has at the end been honored with awesome information to go over with my co-workers. I ‘d admit that we website visitors actually are very fortunate to exist in a superb website with very many marvellous individuals with good basics. I feel quite blessed to have encountered your entire web page and look forward to really more pleasurable minutes reading here. Thanks again for a lot of things.

1. I don’t know who you wrote this for but you helped a brhtoer out.

3. I’m not that much of a online reader to be honest but your sites really nice, keep it up! I’ll go ahead and bookmark your site to come back in the future. Cheers