blaa
blaa

Reputation: 811

BigDecimal math operations

I want to write this in Java but I get some errors and I am not sure how to write it:

C = A - (A*B)/100

All of my values are defined as Bigdecimal objects.

I tried something like this but is not working:

C = A.subtract(A.multiply(B).divide(100));

..I get a warning to add more arguments to the divide method. I do not know how to write it correctly. What am I doing wrong? Thanks in advance

Upvotes: 1

Views: 19407

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1075755

BigDecimal has no divide(int) method, but that's what you're asking it to do with .divide(100), because 100 is an int literal. If you refer to the documentation, all of the divide methods accept BigDecimal instances.

You can use divide(BigDecimal) instead, by using BigDecimal.valueOf:

C = A.subtract(A.multiply(B).divide(BigDecimal.valueOf(100)));

(It accepts a long [or double], but int can be promoted to long.)

Alternately, for some values, you might use the String constructor instead:

C = A.subtract(A.multiply(B).divide(new BigDecimal("100")));

...particularly if you're dealing with floating-point values that might lose precision in double. 100 is fine for valueOf, though.

Upvotes: 6

Pavlo Plynko
Pavlo Plynko

Reputation: 586

c = a.subtract(a.multiply(b).divide(BigDecimal.valueOf(100.0)));

Upvotes: 1

Related Questions