Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding 2 BigDecimal values [duplicate]

class Point {    BigDecimal x;   BigDecimal y;    Point(double px, double py) {     x = new BigDecimal(px);     y = new BigDecimal(py);   }    void addFiveToCoordinate(String what) {     if (what.equals("x")) {       BigDecimal z = new BigDecimal(5);       x.add(z);     }   }    void show() {     System.out.print("\nx: " + getX() + "\ny: " + getY());   }    public BigDecimal getX() {     return x;   }    public BigDecimal getY() {     return y;   }    public static void main(String[] args) {     Point p = new Point(1.0, 1.0);     p.addFiveToCoordinate("x");     p.show();   } } 

Ok, I would like to add 2 BigDecimal values. I'm using constructor with doubles(cause I think that it's possible - there is a option in documentation). If I use it in main class, I get this:

x: 1 y: 1 

When I use System.out.print to show my z variable i get this:

z: 5 
like image 628
Marcin Erbel Avatar asked Jan 13 '12 12:01

Marcin Erbel


People also ask

How do you sum two BigDecimal?

add(BigDecimal val) is used to calculate the Arithmetic sum of two BigDecimals. This method is used to find arithmetic addition of large numbers of range much greater than the range of largest data type double of Java without compromising with the precision of the result.

Can BigDecimal be double?

A BigDecimal is an exact way of representing numbers. A Double has a certain precision. Working with doubles of various magnitudes (say d1=1000.0 and d2=0.001 ) could result in the 0.001 being dropped alltogether when summing as the difference in magnitude is so large. With BigDecimal this would not happen.

How do I append in BigDecimal?

BigDecimal. add(BigDecimal augend, MathContext mc) returns a BigDecimal whose value is (this + augend), with rounding according to the MathContext settings. If either number is zero and the precision setting is nonzero then the other number, rounded if necessary, is used as the result.

How does BigDecimal value multiply?

Use the multiply() method to multiply one BigDecimal to another in Java. This method returns a BigDecimal whose value is (this × multiplicand), and whose scale is (this. scale() + multiplicand.


1 Answers

BigDecimal is immutable. Every operation returns a new instance containing the result of the operation:

 BigDecimal sum = x.add(y); 

If you want x to change, you thus have to do

x = x.add(y); 

Reading the javadoc really helps understanding how a class and its methods work.

like image 102
JB Nizet Avatar answered Oct 06 '22 22:10

JB Nizet