1

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

blaa
  • 801
  • 3
  • 16
  • 32
  • 1
    relevant [javadoc pages](https://docs.oracle.com/javase/8/docs/api/index.html?java/math/BigDecimal.html) –  Feb 23 '17 at 10:34
  • 1
    You are getting the warning "The method divide(BigDecimal) in the type BigDecimal is not applicable for the arguments (int)". Not that you should add more arguments. – OH GOD SPIDERS Feb 23 '17 at 10:35
  • 1
    Possible duplicate of [division of bigdecimal by integer](http://stackoverflow.com/questions/7819553/division-of-bigdecimal-by-integer) – Pavlo Plynko Feb 23 '17 at 10:41

2 Answers2

6

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1
c = a.subtract(a.multiply(b).divide(BigDecimal.valueOf(100.0)));
Pavlo Plynko
  • 586
  • 9
  • 27