如下所示:
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)
发布于 2014-01-21 15:46:40
请注意,常量:
RoundingMode.HALF_UP
BigDecimal.ROUND_HALF_UP
根据Javadoc和源代码,意思完全相同:
public enum RoundingMode {
....
HALF_UP(BigDecimal.ROUND_HALF_UP),
....
}
发布于 2018-06-26 18:33:52
请使用BigDecimal.ROUND_HALF_UP而不是RoundingMode.HALF_UP,因为RoundingMode.HALF_UP在内部调用BigDecimal.ROUND_HALF_UP,所以两者会给出相同的结果,但RoundingMode.HALF_UP需要更多步骤。
来源: java doc:
BigDecimal.ROUND_HALF_UP
public static final RoundingMode HALF_UP舍入模式向“最近邻居”取整,除非两个邻居距离相等,在这种情况下会向上取整。如果丢弃的分数是RoundingMode.UP 0.5,则行为与RoundingMode.DOWN相同;否则,行为与≥相同。请注意,这是学校通常教授的舍入模式。()
RoundingMode.HALF_UP
如果丢弃的分数是>= .5,则公共最终静态int ROUND_HALF_UP的行为与ROUND_UP相同;否则,行为与ROUND_DOWN相同。(舍入到“最近的邻居”,除非两个邻居都是等距离的,在这种情况下向上舍入。) ()
https://stackoverflow.com/questions/19747652
复制相似问题