adding 2 BigDecimal values [duplicate]

社会主义新天地 提交于 2019-12-03 14:35:47

问题


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

回答1:


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.




回答2:


Perhaps this is what you prefer:

BigDecimal z = new BigDecimal(5).add(x);

Every operation of BigDecimal returns a new BigDecimal but not change the current instance.



来源:https://stackoverflow.com/questions/8850441/adding-2-bigdecimal-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!