Skip to content

Instantly share code, notes, and snippets.

@tgruber5150
Created September 11, 2012 18:15
Show Gist options
  • Save tgruber5150/3700469 to your computer and use it in GitHub Desktop.
Save tgruber5150/3700469 to your computer and use it in GitHub Desktop.
Sales Tax Calculator: For either Point-of-Sale or After-the-Sale methods.
import java.text.DecimalFormat;
import java.util.Scanner;
public class SalesTaxInput {
public static void main(String[] args){
System.out.print("What are your taxable sales? ");
double sales = getInput();
sales = SalesTax.roundTwoDecimals(sales);
System.out.print("What is your sales tax rate? 1% = .01: ");
double taxRate = getInput();
String timing = SalesTax.getTimingOfTaxCalculation();
double taxes = 0;
if ("now".equals(timing)) {
taxes = SalesTax.calculateSalesTax(sales, taxRate);
} else if ("later".equals(timing)) {
taxes = SalesTax.calculateTaxAfterTheSale(sales, taxRate);
sales = sales - taxes;
} else {
System.out.println("We didn't recognize your answer. Please try again. ");
}
System.out.println("Total Sales: " + sales);
System.out.println("Total Sales Tax: " + taxes);
System.out.println();
System.out.println("Total amount collected: " + (sales + taxes));
}
public static double getInput(){
Scanner in = new Scanner(System.in);
return in.nextDouble();
}
}
public class SalesTax {
public static double calculateSalesTax(double sales, double taxRate)
{
double i = sales * taxRate;
i = roundTwoDecimals(i);
return i;
}
public static double calculateTaxAfterTheSale(double sales, double taxRate)
{
double i = (sales - (sales/(1+taxRate)));
i = roundTwoDecimals(i);
return i;
}
public static double roundTwoDecimals(double d) {
DecimalFormat twoDForm = new DecimalFormat("#.##");
return Double.valueOf(twoDForm.format(d));
}
public static String getTimingOfTaxCalculation(){
System.out.println("Are you collecting sales tax now, or are you calculating" +
" sales tax based on total collections?");
System.out.print("Please type the word 'Now' or 'Later':");
Scanner in = new Scanner(System.in);
String i = in.next();
i = i.toLowerCase();
return i;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment