使用java.math.MathContext [英] Use of java.math.MathContext
问题描述
最近我尝试了解 java.math.MathContext 的使用,但未能正确理解。它是否用于 java.math.BigDecimal
中的舍入。如果是,为什么不围绕十进制数字,甚至是尾数部分。
Recently I tried understanding the use of java.math.MathContext but failed to understand properly. Is it used for rounding in java.math.BigDecimal
. If yes why does not it round the decimal digits but even mantissa part.
从API文档中,我发现它遵循 ANSI X3.274-1996
和 ANSI X3.274-1996 / AM 1-2000
规格,但我没有让他们在线阅读。
From API docs, I came to know that it follows the standard specified in ANSI X3.274-1996
and ANSI X3.274-1996/AM 1-2000
specifications but I did not get them to read online.
如果您对此有任何疑问,请与我们联系。
Please let me know if you have any idea on this.
推荐答案
@jatan
谢谢你的回答。这说得通。你能否在BigDecimal#round方法的上下文中解释我MathContext。
Thanks for you answer. It makes sense. Can you please explain me MathContext in the context of BigDecimal#round method.
BigDecimal没有什么特别之处。 round()
vs。任何其他 BigDecimal
方法。在所有情况下, MathContext
指定有效位数和舍入技术。基本上,每个 的MathContext
。有一个精确的,还有一个 RoundingMode
。
There's nothing special about BigDecimal.round()
vs. any other BigDecimal
method. In all cases, the MathContext
specifies the number of significant digits and the rounding technique. Basically, there are two parts of every MathContext
. There's a precision, and there's also a RoundingMode
.
精确度再次指定有效位数。因此,如果您指定 123
作为数字,并要求2位有效数字,那么您将获得 120
。如果你考虑科学记数法可能会更清楚。
The precision again specifies the number of significant digits. So if you specify 123
as a number, and ask for 2 significant digits, you're going to get 120
. It might be clearer if you think in terms of scientific notation.
123
将是 1.23e2
科学记数法。如果您只保留2位有效数字,那么您将获得 1.2e2
或 120
。通过减少有效位数,我们降低了指定数字的精度。
123
would be 1.23e2
in scientific notation. If you only keep 2 significant digits, then you get 1.2e2
, or 120
. By reducing the number of significant digits, we reduce the precision with which we can specify a number.
RoundingMode
part指定了我们应该如何处理精度损失。要重复使用该示例,如果您使用 123
作为数字,并要求2位有效数字,则会降低您的精确度。使用 RoundingMode
HALF_UP
(默认模式), 123
将成为 120
。使用 RoundingMode
CEILING
,您将获得 130
。
The RoundingMode
part specifies how we should handle the loss of precision. To reuse the example, if you use 123
as the number, and ask for 2 significant digits, you've reduced your precision. With a RoundingMode
of HALF_UP
(the default mode), 123
will become 120
. With a RoundingMode
of CEILING
, you'll get 130
.
例如:
System.out.println(new BigDecimal("123.4",
new MathContext(4,RoundingMode.HALF_UP)));
System.out.println(new BigDecimal("123.4",
new MathContext(2,RoundingMode.HALF_UP)));
System.out.println(new BigDecimal("123.4",
new MathContext(2,RoundingMode.CEILING)));
System.out.println(new BigDecimal("123.4",
new MathContext(1,RoundingMode.CEILING)));
输出:
123.4
1.2E+2
1.3E+2
2E+2
您可以看到精度和舍入模式都会影响输出。
You can see that both the precision and the rounding mode affect the output.
这篇关于使用java.math.MathContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!