user1438374
user1438374

Reputation:

Using BigDecimal correctly

I'm not sure if I'm doing this right.

I'm doing scientific calculations that need to be accurate as possible so I am converting the existing use of Double to BigDecimal.

// before
double tmp = x - (y / z);

// after
BigDecimal tmp = new BigDecimal(
        x.value().subtract(y.value().divide(z.value())).toString());

Is this logical or what?

Upvotes: 1

Views: 147

Answers (3)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

Assuming that x, y and z are doubles

BigDecimal tmp = new BigDecimal(x).subtract(
           new BigDecimal(y).divide(new BigDecimal(z), MathContext.DECIMAL64));

see BigDecimal.divide API to understand why to use MathContext

Upvotes: 0

Philipp
Philipp

Reputation: 69663

You are doing your arithmetics with doubles before converting the result to BigDecimal. That way you don't gain any precision.

You should convert every number to BigDecimal as soon as possible and then use the methods of BigDecimals (subtract, divide and so on) on the BigDecimal representation to do the arithmetics.

BigDecimal bdX = new BigDecimal(x);
BigDecimal bdY = new BigDecimal(y);
BigDecimal bdZ = new BigDecimal(z);

BigDecimal tmp = bdX.subtract(bdY.divide(bdZ));

Upvotes: 3

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

BigDecimal has methods for all the operators. You should use them instead. You can also control (specify) the scale and rounding.

Avoid using doulbles, instead use BigDecimal from the beginning.

Upvotes: 2

Related Questions