java BigDecimal +=(添加和分配)...如何做到这一点?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17253631/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 01:27:28  来源:igfitidea点击:

BigDecimal += (add and assign) ...How to do this?

javabigdecimal

提问by Terence Chow

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

我似乎无法在 BigDecimal 类中找到“添加和分配”方法。

Is there a method for this?

有没有办法做到这一点?

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

如果你不明白我的问题,我正在尝试这样做:

a += b;

a += b;

but I'm trying to do it with BigDecimals

但我正在尝试使用 BigDecimals

回答by JHS

There is an addmethod in the BigDecimalclass.

类中有一个add方法BigDecimal

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

你必须做—— a = a.add(b);

Have a look at the java docs.

看看java 文档

回答by darijan

I guess you would like something like this:

我想你会喜欢这样的:

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

BigDecimalis immutableobject, so no, you cannot do that.

BigDecimal不可变的对象,所以,你不能这样做。

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

您必须使用add()它并将其等于自身,例如a = a.add(b)

回答by NINCOMPOOP

You can use the BigDecimal#add()method .

您可以使用BigDecimal#add()方法。

a = a.add(b);

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

由于 BigDecimal 是不可变的,因此您不能期望a.add(b)会发生变化a。您必须将新BigDecimal对象返回给引用a。因此a=a.add(b),这就是您所需要的。

回答by jh314

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

BigDecimals 是对象。该+=运算符仅适用于原语。

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

所以我不认为你可以做你想提出的建议。

回答by DaveH

Nope - there is no equivalent mechanism

不 - 没有等效的机制

You just have to use the addmethod

你只需要使用add方法