BigDecimal.ROUND_HALF_UP和RoundingMode.HALF_UP的区别是什么?

6
下面是:
new MathContext(precision, RoundingMode.HALF_UP);

看起来是可以工作的。但是以下代码会返回一个错误:

new MathContext(precision, BigDecimal.ROUND_HALF_UP);

错误:

java: no suitable constructor found for MathContext(int,int)
    constructor java.math.MathContext.MathContext(java.lang.String) is not applicable
      (actual and formal argument lists differ in length)
    constructor java.math.MathContext.MathContext(int,java.math.RoundingMode) is not applicable
      (actual argument int cannot be converted to java.math.RoundingMode by method invocation conversion)
    constructor java.math.MathContext.MathContext(int) is not applicable
      (actual and formal argument lists differ in length)

4
其中一个是“RoundingMode”,另一个是“BigDecimal”的“int”字段——错误信息已经告诉你了。你的问题还有其他方面需要解决吗? - Boris the Spider
为什么一个是 RoundingMode,而另一个是 int?这两者之间有什么区别?http://docs.oracle.com/javase/7/docs/api/java/math/RoundingMode.html 实际上并没有解释任何东西。 - user2948708
1
因为MathContext是Java数学API的一部分,而RoundingMode也是如此。BigDecimalROUND_HALF_UP字段是BigDecimal自己的实现细节。 - Boris the Spider
所以它们都只是整数,只是一个具有类型“RoundingMode”,另一个具有类型“int”?如果我将“RoundingMode”强制转换为“int”,它会起作用吗? “RoundingMode”只是一个整数枚举,对吧? - user2948708
2
为什么不看一下代码呢?谷歌是你的朋友。RoundingMode是一个枚举类型。实际上,快速浏览代码就可以告诉你,RoundingMode.valueOf(BigDecimal.ROUND_HALF_UP) == RoundingMode.HALF_UP。事实上,代码中的注释是:_返回与传统舍入模式对应的RoundingMode对象_(强调是我的)。 - Boris the Spider
1
枚举在Java中是类,不是整数。搜索Java的枚举教程并阅读它。如果一个变量具有RoundingMode类型,则其类型为RoundingMode而不是int。 - JB Nizet
2个回答

3
请注意以下常量:

RoundingMode.HALF_UP
BigDecimal.ROUND_HALF_UP

根据Javadocs和源代码,完全相同的意思:

public enum RoundingMode {
....
HALF_UP(BigDecimal.ROUND_HALF_UP),
....
} 

-2
请使用BigDecimal.ROUND_HALF_UP而不是RoundingMode.HALF_UP,因为RoundingMode.HALF_UP在内部调用BigDecimal.ROUND_HALF_UP,所以两者将给出相同的结果,但RoundingMode.HALF_UP需要多一步操作。
来自Java文档的来源:

BigDecimal.ROUND_HALF_UP

public static final RoundingMode HALF_UP
向最近的邻居舍入的舍入模式,除非两个邻居都等距离,否则向上舍入。 如果弃小数≥0.5,则行为与RoundingMode.UP相同; 否则,行为与RoundingMode.DOWN相同。 注意,这是通常在学校教授的舍入模式。(单击此处了解更多信息

RoundingMode.HALF_UP

public final static int ROUND_HALF_UP 如果被舍弃的小数>=0.5,则像ROUND_UP一样行为;否则,像ROUND_DOWN一样行为。(向“最近邻居”四舍五入,除非两个相邻的值相等,在这种情况下进行上舍入。)(点击此处了解更多)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接