Skip to content

Instantly share code, notes, and snippets.

@tobyweston
Created September 16, 2012 17:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tobyweston/3733479 to your computer and use it in GitHub Desktop.
Save tobyweston/3733479 to your computer and use it in GitHub Desktop.
Sales tax calculations
public class TaxRate extends AbstractValueType<Double> {
public static TaxRate taxRate(Double value) {
return new TaxRate(value);
}
private TaxRate(Double value) {
super(value);
}
public TaxAmount paidOn(GrossAmount gross) {
Double rate = asDecimal();
Double tax = gross.value() / (1 + rate) * rate;
return taxAmount(tax);
}
private Double asDecimal() {
return value() / 100;
}
}
public class TaxRateTest {
@Test
public void shouldCalculateTaxPaidOnGrossAmount() {
assertThat(taxRate(0.0).paidOn(grossAmount(9.99)), is(taxAmount(0.0)));
assertThat(taxRate(17.5).paidOn(grossAmount(9.99)), is(taxAmount(1.4878723404255318)));
assertThat(taxRate(20.0).paidOn(grossAmount(9.70)), is(taxAmount(1.616666666666667)));
assertThat(taxRate(20.0).paidOn(grossAmount(3.24)), is(taxAmount(0.54)));
assertThat(taxRate(100.0).paidOn(grossAmount(100.0)), is(taxAmount(50.0)));
}
}
public class TaxAmount extends AbstractValueType<Double> {
public static TaxAmount taxAmount(Double value) {
return new TaxAmount(value);
}
private TaxAmount(Double value) {
super(value);
}
public TaxRate paidOn(GrossAmount gross) {
Double amount = value();
Double net = gross.value() - amount;
double rate = (amount / net) * 100;
return taxRate(rate);
}
}
public class TaxAmountTest {
@Test
public void shouldWorkSucker() {
assertThat(taxAmount(0.73).paidOn(grossAmount(4.35)), is(taxRate(20.0)));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment