8

I want to divide a bigdecimal value with an integer.i have rounded the bigdecimal value(if it is 133.333 then rounded value is 133).given below is my code snippet.

v1 = v1.setScale(0, RoundingMode.HALF_UP);
int temp = BigDecimal.valueOf(v1.longValue()).divide(constant1);

value of constant is 12. It is showing an error message that

The method divide(BigDecimal) in the type BigDecimal is not applicable for the arguments (int)

Can anyone help me to do the division?

aioobe
  • 413,195
  • 112
  • 811
  • 826
andro-girl
  • 7,989
  • 22
  • 71
  • 94

2 Answers2

9

Change

.divide(constant1);

to

.divide(new BigDecimal(constant1));

Btw, why don't you just do something like

int temp = (int) (Math.round(v1.doubleValue()) / constant1);

??

aioobe
  • 413,195
  • 112
  • 811
  • 826
  • i tried this...but now it is showing that i have to change the datatype of temp as bigdecimal. – andro-girl Oct 19 '11 at 10:05
  • right, so append `.intValue()` on the end of the line then if you don't want to do this. – aioobe Oct 19 '11 at 10:10
  • since the wanted result (apparently) is an `int`, better do `int temp = Math.round(v1.longValue()) / constant1;`, or? – user85421 Oct 19 '11 at 11:05
  • Sure. Assuming you intended to write `doubleValue`, you need a cast for that line to compile though – aioobe Oct 19 '11 at 11:10
  • i cant change the datatype of temp.bcz it is using somewhere else – andro-girl Oct 19 '11 at 11:16
  • Try my last (updated) line. `temp` is an `int`, and I believe it performs the same operation. – aioobe Oct 19 '11 at 11:21
  • actually I intended to write `floatValue` so no cast needed at all (BTW if you do not use @Carlos in the comment-answer I will not be notified...) – user85421 Oct 20 '11 at 11:48
0

You should write the code as follows:

int temp = BigDecimal.valueOf(v1.longValue())
        .divide(BigDecimal.valueOf(constant1)).intValue();

The thing about BigDecimal and BigInteger is that they mostly operate with instances of these classes and not with primitive types. Results of operations are also new instances of these classes.

One other remark: I advise to use valueOf static method instead of a constructor, because by doing this you may have a possibility to avoid creation of new objects. Using a constructor makes creation of a new object explicit, which is not necessary in this case at all.

Malcolm
  • 41,014
  • 11
  • 68
  • 91
  • i am getting this exception when i tried this code10-19 16:28:42.375: ERROR/AndroidRuntime(479): java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result – andro-girl Oct 19 '11 at 11:13
  • Take a look at this question: http://stackoverflow.com/questions/4591206/non-terminating-decimal-expansion-no-exact-representable-decimal-result , it is shown there how to avoid such errors by using rounding. – Malcolm Oct 19 '11 at 13:12