Search code examples
javabigdecimal

Decimal Precision Issue | Big Decimal


1.

    BigDecimal ap = new BigDecimal(170.8999999999998,   MathContext.DECIMAL64).setScale(2, BigDecimal.ROUND_FLOOR);

result : 170.89 (Required : 170.89)

2.

    BigDecimal ap = new BigDecimal(170.89999999999998, MathContext.DECIMAL64).setScale(2, BigDecimal.ROUND_FLOOR); (1 Extra 9 in value)

result : 170.90 (Required : 170.89)

3.

    BigDecimal ap = new BigDecimal(2401.99).setScale(2, BigDecimal.ROUND_FLOOR);

result : 2401.98 (Required : 2401.99)

How to get just 2 digit after decimal from value without rounding.

P.S : I do not want to convert the value to String.


Solution

  • 2401.99 is a double literal, with an actual value just below that.

    Use the BigDecimal constructor from a String instead.