31

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);
   }
}
Vaandu
  • 4,857
  • 12
  • 49
  • 75
cutrightjm
  • 657
  • 2
  • 6
  • 20
  • 8
    As it seems like it is homework I'll give just a hint: *Use DecimalFormat class.* – Harry Joy Jan 17 '12 at 13:24
  • What's the problem in using class provided by Java? It is not any third party class. – Harry Joy Jan 17 '12 at 13:28
  • 1
    duplicate of http://stackoverflow.com/questions/8819842/best-way-to-format-a-double-value-to-2-decimal-places – Rajesh Pantula Jan 17 '12 at 13:29
  • IRL you shouldn't use floating point numbers for monetary calculations. Use BigDecimal/long/int instead. See http://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency – COME FROM Jan 17 '12 at 13:55

8 Answers8

60

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

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
Alex
  • 2,405
  • 4
  • 23
  • 36
12

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);
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
5

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.

Jeremiah Orr
  • 2,620
  • 1
  • 18
  • 24
1

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();

}
Tahir Ferli
  • 636
  • 4
  • 16
0

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?

0

Use this method decimalPoint like

System.out.print("$" + ReduceDecimalValue.decimalPoint(shippingCost));

I think this is a efficient way to reduce the decimal points from given double value.

class ReduceDecimalValue {
    public static void main(String[] args) {
        
        double value = 12222.934817359387;
        System.out.println(ReduceDecimalValue.decimalPoint(value, 3));
    }

    static double decimalPoint(double value, int count) {// value: 12222.934817359387, count: 3
        // Splitting the real and decimal values.
        long real = (long) value;                   // real: 12222
        double floats = value - real;               // floats: 0.934817359387

        double point = Math.pow(10, count);         // point: 100
        // multiplying with 10 increased by count to move the decimal point to right.
        // typecast by long will remove the decimal value. and converting the value to decimal points(0.934)
        floats = ((long)(floats * point)) / point;  // floats:  ((long)(934.817359387)) / 100
                                                    //          =>  934 / 100  =>  0.934
        return real + floats;                       // 12222.934
    }
}
0

Use the DecimalFormat class to format the double

Jrom
  • 849
  • 1
  • 10
  • 19
0

You use the String.format() method.

Wernsey
  • 5,411
  • 22
  • 38