Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid Price.toString() failing for certain values of numerator/denominator. #498

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion app/src/main/java/org/gnucash/android/model/Price.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@


import java.math.BigDecimal;
import java.math.MathContext;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.NumberFormat;
Expand Down Expand Up @@ -156,6 +157,6 @@ public String toString() {
BigDecimal denominator = new BigDecimal(mValueDenom);
DecimalFormat formatter = (DecimalFormat) NumberFormat.getNumberInstance();
formatter.setMaximumFractionDigits(6);
return formatter.format(numerator.divide(denominator));
return formatter.format(numerator.divide(denominator, MathContext.DECIMAL32));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import java.util.Locale;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;


public class PriceTest {
Expand Down Expand Up @@ -52,6 +53,26 @@ public void toString_shouldUseDefaultLocale() {
assertThat(price.toString()).isEqualTo("1,234");
}

/**
* BigDecimal throws an ArithmeticException if it can't represent exactly
* a result. This can happen with divisions like 1/3 if no precision and
* round mode is specified with a MathContext.
*/
@Test
public void toString_shouldNotFailForInfinitelyLongDecimalExpansion() {
long numerator = 1;
long denominator = 3;
Price price = new Price();

price.setValueNum(numerator);
price.setValueDenom(denominator);
try {
price.toString();
} catch (ArithmeticException e) {
fail("The numerator/denominator division in Price.toString() should not fail.");
}
}

@Test
public void getNumerator_shouldReduceAutomatically() {
long numerator = 1;
Expand Down