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); } }
Now you can limit the decimal places. Select the cell with a number (here, B2) and in the Menu, go to Format > Number > More Formats > Custom number format.
By using a button: Select the cells that you want to format. On the Home tab, click Increase Decimal or Decrease Decimal to show more or fewer digits after the decimal point.
Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places.
Use a DecimalFormatter:
double number = 0.9999999999999; DecimalFormat numberFormat = new DecimalFormat("#.00"); System.out.println(numberFormat.format(number));
Will give you "0.99". You can add or subtract 0 on the right side to get more or less decimals.
Or use '#' on the right to make the additional digits optional, as in with #.## (0.30) would drop the trailing 0 to become (0.3).
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With