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());
}
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.
Since BigDecimal is immutable, these operations do not modify the existing objects. Rather, they return new objects.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With