user2948708
user2948708

Reputation: 115

Difference between BigDecimal.ROUND_HALF_UP and RoundingMode.HALF_UP?

The below:

new MathContext(precision, RoundingMode.HALF_UP);

seems to work. However, the following returns an error:

new MathContext(precision, BigDecimal.ROUND_HALF_UP);

Error:

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)

Upvotes: 6

Views: 16208

Answers (2)

Ganesa Vijayakumar
Ganesa Vijayakumar

Reputation: 2602

Please use BigDecimal.ROUND_HALF_UP instead of RoundingMode.HALF_UP because of RoundingMode.HALF_UP is calling BigDecimal.ROUND_HALF_UP internally so both will give you same result but RoundingMode.HALF_UP will require one more step.

Sources from java doc:

BigDecimal.ROUND_HALF_UP

public static final RoundingMode HALF_UP Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up. Behaves as for RoundingMode.UP if the discarded fraction is ≥ 0.5; otherwise, behaves as for RoundingMode.DOWN. Note that this is the rounding mode commonly taught at school. (click here to know more)

RoundingMode.HALF_UP

public final static int ROUND_HALF_UP Behave as for ROUND_UP if the discarded fraction is >= .5; otherwise, behave as for ROUND_DOWN. (Rounds towards "nearest neighbor" unless both neighbors are equidistant, in which case rounds up.) (click here to know more)

Upvotes: -2

Vladimir Petrovich
Vladimir Petrovich

Reputation: 31

Please note that the constants:

RoundingMode.HALF_UP
BigDecimal.ROUND_HALF_UP

mean absolutely the same according to Javadocs and according to source code:

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

Upvotes: 3

Related Questions