This program works, except when the number of nJars is a multiple of 7, I will get an answer like $14.999999999999998. For 6, the output is 14.08. How do I fix exceptions for multiples of 7 so it will display something like $14.99?
import java.util.Scanner;
public class Homework_17
{
private static int nJars, nCartons, totalOunces, OuncesTolbs, lbs;
public static void main(String[] args)
{
computeShippingCost();
}
public static void computeShippingCost()
{
System.out.print("Enter a number of jars: ");
Scanner kboard = new Scanner (System.in);
nJars = kboard.nextInt();
int nCartons = (nJars + 11) / 12;
int totalOunces = (nJars * 21) + (nCartons * 25);
int lbs = totalOunces / 16;
double shippingCost = ((nCartons * 1.44) + (lbs + 1) * 0.96) + 3.0;
System.out.print("$" + shippingCost);
}
}
Check out DecimalFormat: http://docs.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html
You'll do something like:
new DecimalFormat("$#.00").format(shippingCost);
Or since you're working with currency, you could see how NumberFormat.getCurrencyInstance()
works for you.
If you want to print/write double value at console then use System.out.printf()
or System.out.format()
methods.
System.out.printf("\n$%10.2f",shippingCost);
System.out.printf("%n$%.2f",shippingCost);
Formatter class is also a good option. fmt.format("%.2f", variable); 2 here is showing how many decimals you want. You can change it to 4 for example. Don't forget to close the formatter.
private static int nJars, nCartons, totalOunces, OuncesTolbs, lbs;
public static void main(String[] args)
{
computeShippingCost();
}
public static void computeShippingCost()
{
System.out.print("Enter a number of jars: ");
Scanner kboard = new Scanner (System.in);
nJars = kboard.nextInt();
int nCartons = (nJars + 11) / 12;
int totalOunces = (nJars * 21) + (nCartons * 25);
int lbs = totalOunces / 16;
double shippingCost = ((nCartons * 1.44) + (lbs + 1) * 0.96) + 3.0;
Formatter fmt = new Formatter();
fmt.format("%.2f", shippingCost);
System.out.print("$" + fmt);
fmt.close();
}
okay one other solution that I thought of just for the fun of it would be to turn your decimal into a string and then cut the string into 2 strings, one containing the point and the decimals and the other containing the Int to the left of the point. after that you limit the String of the point and decimals to 3 chars, one for the decimal point and the others for the decimals. then just recombine.
double shippingCost = ((nCartons * 1.44) + (lbs + 1) * 0.96) + 3.0;
String ShippingCost = (String) shippingCost;
String decimalCost = ShippingCost.subString(indexOf('.'),ShippingCost.Length());
ShippingCost = ShippingCost.subString(0,indexOf('.'));
ShippingCost = ShippingCost + decimalCost;
There! Simple, right?
You use the String.format() method.
Use the DecimalFormat class to format the double
Source: Stackoverflow.com