user10297
user10297

Reputation: 149

How do force BigDecimal from rounding in JUnit assertEquals?

Everytime I run my assertEquals, my expected BigDecimal is being rounded which causes it to fail. How do I make sure it doesn't round or is there another way?

@Test
public void test() {
    BigDecimal amount = BigDecimal.valueOf(1000);
    BigDecimal interestRate = BigDecimal.valueOf(10);
    BigDecimal years = BigDecimal.valueOf(10);
    InterestCalculator ic = new InterestCalculate(amount, interestRate, years);
    BigDecimal expected = BigDecimal.valueOf(1321.507369947139705200000);
    assertEquals(expected, ic.getMonthlyPaymentAmount());
}

Upvotes: 7

Views: 8031

Answers (1)

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79857

Put it in quotation marks and use the BigDecimal constructor.

BigDecimal expected = new BigDecimal("1321.507369947139705200000");

If you don't do this, the number gets converted to a double first, and then to a BigDecimal, because 1321.507369947139705200000 is a double literal. That's really not what you want.

Upvotes: 20

Related Questions