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
BigDecimal += (add and assign) ...How to do this?
提问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
回答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方法

