Java BigDecimal setScale 和 round
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3843440/
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 setScale and round
提问by user
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 BigDecimal("3.53456").setScale(4, RoundingMode.HALF_UP);
采纳答案by dale peters
One important point that is alluded to but not directly addressed is the difference between "precision"and "scale"and how they are used in the two statements. "precision"is the total number of significant digits in a number. "scale"is the number of digits to the right of the decimal point.
提到但没有直接解决的一个重要问题是“精度”和“比例”之间的区别以及它们在两个语句中的使用方式。 “精度”是数字中有效数字的总数。 “scale”是小数点右边的位数。
The MathContext constructor only accepts precision and RoundingMode as arguments, and therefore scale is never specified in the first statement.
MathContext 构造函数只接受精度和 RoundingMode 作为参数,因此在第一条语句中从未指定比例。
setScale()
obviously accepts scale as an argument, as well as RoundingMode, however precision is never specified in the second statement.
setScale()
显然接受 scale 作为参数,以及 RoundingMode,但是在第二个语句中从未指定精度。
If you move the decimal point one place to the right, the difference will become clear:
如果你把小数点向右移动一位,区别就很明显了:
// 1.
new BigDecimal("35.3456").round(new MathContext(4, RoundingMode.HALF_UP));
//result = 35.35
// 2.
new BigDecimal("35.3456").setScale(4, RoundingMode.HALF_UP);
// result = 35.3456
回答by user817756
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:
确实有很大的不同,你应该记住这一点。setScale 确实设置了您的数字的比例,而 round 确实将您的数字四舍五入到指定的数字,但如 jdk 中所述,它“从精确结果的最左边数字开始”。因此,对于您的样本,结果是相同的,但请尝试使用 0.0034。这是我在我的博客上的注释:
http://araklefeistel.blogspot.com/2011/06/javamathbigdecimal-difference-between.html
http://araklefeistel.blogspot.com/2011/06/javamathbigdecimal-difference-between.html