如何在java中乘以和除以BigDecimal后得到精确值

时间:2014-05-15 10:24:32

标签: java rounding bigdecimal

import java.math.*;

public class Test{
public static void main(String args[]){

BigDecimal initialValue = BigDecimal.valueOf(193);
BigDecimal divider = BigDecimal.valueOf(3);
BigDecimal result = initialValue.divide(divider, 2, RoundingMode.HALF_UP);
System.out.println(initialValue + " / " + divider+" = "+result);
BigDecimal retriveInitialValue = result.multiply(divider);
System.out.println(result + " * " + divider+" = "+retriveInitialValue);

}
}

输出我得到了 193/3 = 64.33

64.33 * 3 = 192.99

我所期待的 193/3 = 64.33

64.33 * 3 = 193

3 个答案:

答案 0 :(得分:1)

在实现一些class Rational之前,你不能得到这个结果,它将包含分子和分母。每次计算都是精确的。此外,您可以将其四舍五入以获得接近的整数。

答案 1 :(得分:0)

更改此行:

BigDecimal retriveInitialValue = result.multiply(divider);

...到......

BigDecimal retriveInitialValue = result.multiply(divider).setScale(0, RoundingMode.HALF_UP);

<强>输出

64.33 * 3 = 193

答案 2 :(得分:0)

org.jscience.mathematics.number.FloatingPoint initialValue =  org.jscience.mathematics.number.FloatingPoint.valueOf("145.123456789");
org.jscience.mathematics.number.FloatingPoint divideWith =   org.jscience.mathematics.number.FloatingPoint.valueOf("3");
org.jscience.mathematics.number.FloatingPoint result = initialValue.divide(divideWith); 
System.out.println(result.doubleValue() );
org.jscience.mathematics.number.FloatingPoint finalResult = result.times(divideWith);
System.out.println(finalResult.doubleValue() );