Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
629 views
in Technique[技术] by (71.8m points)

java - BigDecimal scale not working

I have the following code:

BigDecimal result = BigDecimal.ZERO;
result.setScale(2, BigDecimal.ROUND_FLOOR); //1
BigDecimal amountSum;

// amount sum computation

BigDecimal amountByCurrency = amountSum.divide(32); //-0.04
result.add(amountByCurrency); //2

After line //1 scale is still 0. Why? So, the //2 evaluation doesn't affect to the result. What's wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The important part of the #setScale documentation is this:

Note that since BigDecimal objects are immutable, calls of this method do not result in the original object being modified, contrary to the usual convention of having methods named setX mutate field X. Instead, setScale returns an object with the proper scale; the returned object may or may not be newly allocated.

(emphasis added)

Therefore, this line in your code won't change the result instance:

result.setScale(2, BigDecimal.ROUND_FLOOR); //1

Either change it to:

result = result.setScale(2, BigDecimal.ROUND_FLOOR);

to overwrite the instance with the new one, or create a new variable and use that instead of result:

BigDecimal scaledResult = result.setScale(2, BigDecimal.ROUND_FLOOR);

Btw: the same applies to this line:

result.add(amountByCurrency); //2

You need to store the returned BigDecimal instance of the #add call in a variable.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...