Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I limit the number of decimals printed for a double?

Tags:

java

int

double

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);    } } 
like image 817
cutrightjm Avatar asked Jan 17 '12 13:01

cutrightjm


People also ask

How do you restrict decimals?

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.

How do I restrict double to 3 decimal places in Excel?

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.

How do you print 2 decimal places only?

Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places.


2 Answers

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).

like image 64
Alex Avatar answered Oct 07 '22 14:10

Alex


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); 
like image 32
KV Prajapati Avatar answered Oct 07 '22 13:10

KV Prajapati