11

I can't seem to locate an 'add and assign' method in the BigDecimal class.

Is there a method for this?

In case you don't understand my question I'm trying to do this:

a += b;

but I'm trying to do it with BigDecimals

Terence Chow
  • 10,755
  • 24
  • 78
  • 141
  • 2
    First google result for `java bigdecimal add` gave me [adding-2-bigdecimal-values](http://stackoverflow.com/questions/8850441/adding-2-bigdecimal-values). – Pshemo Jun 22 '13 at 17:52
  • you can't use the regular `+-*/` operators for BigDecimals as they are not primitives. tbh it sucks, its probably my top 1 most hated thing about Java (even tho I love it) – 0x6C38 Jun 22 '13 at 17:54

5 Answers5

22

There is an add method in the BigDecimal class.

You would have to do - a = a.add(b);

Have a look at the java docs.

JHS
  • 7,761
  • 2
  • 29
  • 53
  • Thank you that both answers my questions and shows me what I need to do. Silly me, can't believe I didn't think of this. Thank you! – Terence Chow Jun 22 '13 at 17:53
  • In case you want for details. BigDecimal is a class same as Integer. Now in Java there is a primitive type for Integer which is int. So for int you can do what you want to i.e. the +=, however for BigDecimal and Integer you cannot do. – JHS Jun 22 '13 at 17:56
  • no I understand I just assumed that someone would have written that operator as a method for the BigDecimal class similar to the way in C++ you can write methods for any class to use the +,-,*,/ and assignment operators. Based on the answers here I'm assuming that you cannot do that – Terence Chow Jun 22 '13 at 18:09
10

I guess you would like something like this:

BigDecimal bd = getNumber();
bd.addAndAssign(5);

BigDecimal is an immutable object, so no, you cannot do that.

You must use add() and equal it to itself, e.g. a = a.add(b)

darijan
  • 9,725
  • 25
  • 38
2

You can use the BigDecimal#add() method .

a = a.add(b);

Since BigDecimal is immutable , you cannot expect a.add(b) to mutate a . You have to return the new BigDecimal object to the reference a . Hence a=a.add(b) is what you need.

AllTooSir
  • 48,828
  • 16
  • 130
  • 164
1

BigDecimals are objects. the += operator only works with primitives.

So I don't think you can do what you are trying to propose.

jh314
  • 27,144
  • 16
  • 62
  • 82
  • That's not true in java > 1.5 with autoboxing you can use with WrapperClass for example Integer Double.. – nachokk Jun 22 '13 at 18:18
0

Nope - there is no equivalent mechanism

You just have to use the add method

DaveH
  • 7,187
  • 5
  • 32
  • 53