Solved

Add two BigDecimal values

Posted on 2007-11-22
4
1,322 Views
Last Modified: 2013-12-29
Hello,

I expected in the folowing code "totalN" to be 52.75,
thank you for any help.

BigDecimal totalN = new BigDecimal("0");
totalN.add(nR1);
System.err.println(nR1.doubleValue());      // 52.75
System.err.println(totalN.doubleValue());  // 0.0
0
Comment
Question by:matthew016
  • 2
4 Comments
 
LVL 7

Accepted Solution

by:
UrosVidojevic earned 380 total points
ID: 20335553
try:

totalN = totalN.add(nR1);
0
 
LVL 7

Expert Comment

by:UrosVidojevic
ID: 20335573
From java documentation:

add

public BigDecimal add(BigDecimal val)

    Returns a BigDecimal whose value is (this + val), and whose scale is max(this.scale(), val.scale()).

    Parameters:
        val - value to be added to this BigDecimal.
    Returns:
        this + val

In other words number1.add(number2) doesn't modify number1 object!
0
 
LVL 9

Assisted Solution

by:ysnky
ysnky earned 20 total points
ID: 20335616
you have to catch add operation result. try this;

            BigDecimal nR1 = new BigDecimal(52.75);
            BigDecimal totalN = new BigDecimal("0");
            totalN = totalN.add(nR1);

            System.err.println(nR1.doubleValue());      
            System.err.println(totalN.doubleValue());
0
 
LVL 17

Assisted Solution

by:contactkarthi
contactkarthi earned 100 total points
ID: 20336285
have a look at this one to get a more understanding on why..
http://www.javaranch.com/journal/2003/04/immutable.htm
0

Featured Post

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

776 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question