Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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());
}
like image 359
user10297 Avatar asked Dec 17 '13 22:12

user10297


People also ask

How do you assert the big decimal?

The official junit solution to assert that two BigDecimal are matematically equal is to use hamcrest. Show activity on this post. assertSame checks if both objects are the same instance. assertEquals checks if the numbers are equal in value and scale, that means i.e. 1000 is not equal to 1000.00.

Is BigDecimal immutable in Java?

Since BigDecimal is immutable, these operations do not modify the existing objects. Rather, they return new objects.

How to represent BigDecimal in Java?

BigDecimal(char[ ] in, int offset, int len) This constructor is used to translate a character array representation of a BigDecimal into a BigDecimal, accepting the same sequence of characters as the BigDecimal(String) constructor, while allowing a sub-array to be specified.

How many digits in BigDecimal?

A BigDecimal consists of an arbitrary precision integer unscaled value and a 32-bit integer scale. If zero or positive, the scale is the number of digits to the right of the decimal point. If negative, the unscaled value of the number is multiplied by ten to the power of the negation of the scale.


1 Answers

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.

like image 183
Dawood ibn Kareem Avatar answered Sep 22 '22 01:09

Dawood ibn Kareem