BigDecimal don't understand, doesn't add up right

E

epicwinter

I don't understand how I am suppose to use the bigdecimal class. If i
do this:
BigDecimal total = new BigDecimal(0);
total.add(new BigDecimal(100));
total.add(new BigDecimal(112.222));
System.err.println("total: " +new Double(total.setScale(2,
java.math.BigDecimal.ROUND_HALF_UP).doubleValue()));

The output is zero. Why? Everytime you intialize the big decimal to
zero it won't function?
 
O

Oliver Wong

I don't understand how I am suppose to use the bigdecimal class. If i
do this:
BigDecimal total = new BigDecimal(0);
total.add(new BigDecimal(100));
total.add(new BigDecimal(112.222));
System.err.println("total: " +new Double(total.setScale(2,
java.math.BigDecimal.ROUND_HALF_UP).doubleValue()));

The output is zero. Why? Everytime you intialize the big decimal to
zero it won't function?

BigDecimal is immutable. When you do total.add(new BigDecimal(100)),
you're not changing the value. Rather, a new BigDecimal object is created
and returned, but you're throwing away this new object. You should write
your code as:

total = total.add(new BigDecimal(100));

for example.

- Oliver
 
M

Mike Schilling

I don't understand how I am suppose to use the bigdecimal class. If i
do this:
BigDecimal total = new BigDecimal(0);
total.add(new BigDecimal(100));
total.add(new BigDecimal(112.222));
System.err.println("total: " +new Double(total.setScale(2,
java.math.BigDecimal.ROUND_HALF_UP).doubleValue()));

The output is zero. Why? Everytime you intialize the big decimal to
zero it won't function?

BigDecimals are immutable, like strings.

Try::

total = total.add(new BigDecimal(100));
etc.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,608
Members
45,241
Latest member
Lisa1997

Latest Threads

Top