BigDecimal setScale and round

后端 未结 2 850
独厮守ぢ
独厮守ぢ 2020-11-29 17:19

What is the difference between this two call? (Is there any?)

// 1.
new BigDecimal(\"3.53456\").round(new MathContext(4, RoundingMode.HALF_UP));
// 2.
new Bi         


        
2条回答
  •  甜味超标
    2020-11-29 17:45

    There is indeed a big difference, which you should keep in mind. setScale really set the scale of your number whereas round does round your number to the specified digits BUT it "starts from the leftmost digit of exact result" as mentioned within the jdk. So regarding your sample the results are the same, but try 0.0034 instead. Here's my note about that on my blog:

    http://araklefeistel.blogspot.com/2011/06/javamathbigdecimal-difference-between.html

提交回复
热议问题