I am fairly new to java and I have to create this program to which I have no idea where to start. Can someone please help me with what to do and how to write the code to get
You can use the format() method instead of println()
:
System.out.format("The subtotal is $%.2f%n", total);
A description of the format syntax can be found here.
Never use double
for money, user BigDecimal
!
Java has a DecimalFormat class for things like this.
http://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html
So you would want to add to your code
DecimalFormat df = new DecimalFormat("###,##0.00");
and change your output to
double totalwotax = (total * tax );
System.out.println("The tax for the subtotal is $" + df.format(totalwotax));
double totalandtax = (total + totalwotax);
System.out.println("The total for your bill with tax is $" + df.format(totalandtax));
This will ensure there are exactly two digits to the right of the decimal point for your cents, and keep at least one to the left in case the total is under a dollar. If its 1,000 or above, it will be formatted with the comma in the right place. Should your totals be higher than 1 million, you might have to alter it to something like this to get the extra comman
DecimalFormat df = new DecimalFormat("###,###,##0.00");
EDIT: So Java also has built-in support for formatting currency. Forget the DecimalFormatter and use the following:
NumberFormat nf = NumberFormat.getCurrencyInstance();
And then use it just as you would the DecimalFormatter, but without the preceding dollar sign (it will be added by the formatter)
System.out.println("The total for your bill with tax is " + nf.format(totalandtax));
Additionally, this method is locale-sensitive, so if you're in the US it will use dollars, if in Japan it uses yen, and so on.
You could simply try this one
DecimalFormat df=new DecimalFormat("#.##");
For Tax
double totalwotax = 0.8130000000000001;
System.out.println("The tax for the subtotal is $" + df.format(totalwotax));
Output: 0.81
For Total
double totalandtax = 14.363000000000001;
System.out.println("The total for your bill with tax is $" + df.format(totalandtax));
Output: 14.36