mimichaelckc
mimichaelckc

Reputation: 33

How to properly calculate rational by using BigDecimal

How can I get the correct answer when I need to use BigDecimal without losing precision.

BigDecimal a = new BigDecimal(0.5);
BigDecimal b = new BigDecimal(30);
BigDecimal c = new BigDecimal(18000);

a.divide(b).multiply(c);

How could I get the exact 300 in this case?

Thanks!

Upvotes: 2

Views: 158

Answers (1)

bramh
bramh

Reputation: 638

You can use the MathContext parameter in the divide method for this.

For example, a.divide(b, MathContext.DECIMAL128).multiply(c); will give you the precision you need (with an error of magnitude 1e-32). If you do not want to lose any precision, you can use MathContext.UNLIMITED, but this will result in a non-terminating decimal expansion.

In your case specifically, you can also try to rewrite the equation to prevent any rounding from happening: a / b * c = c / b * a.

Upvotes: 2

Related Questions