How do I limit the number of decimals printed for a double?
Solution 1
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).
Solution 2
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);
Solution 3
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.
Solution 4
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();
}
cutrightjm
Updated on July 20, 2022Comments
-
cutrightjm almost 2 years
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); } }