tenten
tenten

Reputation: 1276

Setting 2 decimal places in double value in Java

I get the values from the j table. I want to show cost in 2 decimal places and qty in no decimal places.

Currently both outputs one decimal place(123.0)

How to fix this;

DecimalFormat df= new DecimalFormat("0.00");    

            int i = tableSale.getRowCount();        
            String id = (String) tableSale.getValueAt(i-1, 0);
            String name = (String) tableSale.getValueAt(i-1, 1);
            double dcost =  (double) tableSale.getValueAt(i-1, 2);
            double cst=Double.valueOf(df.format(dcost));//setting 2 decimal places
            String cost = String.valueOf(cst);//converting double to string

            double dqty = (double) tableSale.getValueAt(i-1, 3);
            DecimalFormat dd=new DecimalFormat("0");
            double qt = Double.valueOf(dd.format(dqty));
            String qty = String.valueOf(dqty);//converting double to string

            double ditemDiscount = (double) tableSale.getValueAt(i-1, 4);
            String itemDiscount = String.valueOf(ditemDiscount);//converting double to string

            double dgrossTotal = (double) tableSale.getValueAt(i-1, 5);
            double gTotal=Double.valueOf(df.format(dgrossTotal));//setting 2 decimal places
            String grossTotal = String.valueOf(gTotal);//converting double to string

Upvotes: 1

Views: 1444

Answers (5)

Peter Lawrey
Peter Lawrey

Reputation: 533472

If you want to round to 2 decimal places you can use this function.

double dcost = round2(tableSale.getValueAt(i-1, 2));

This avoids the overhead of formatting a string just so you can parse it.

private static final double WHOLE_NUMBER = 1L << 53;
public static double round2(double d) {
    final double factor = 1e2;
    return d > WHOLE_NUMBER || d < -WHOLE_NUMBER ? d :
            (long) (d < 0 ? d * factor - 0.5 : d * factor + 0.5) / factor;
}

You can adjust the factor to taste.

Upvotes: 0

Kenny Tai Huynh
Kenny Tai Huynh

Reputation: 1599

I think you can use this:

 double dcost =  (double) tableSale.getValueAt(i-1, 2);
 String text = new DecimalFormat("##.##").format(dcost);

For the same with the rest double values.

Hope this help!

Upvotes: 2

Rustam
Rustam

Reputation: 6515

try

String.format("%.2f", 123.0) //for two decimal point.

and

String.format("%.0f", 123.0)// for no decimal point.

output:

  123.00
  123

Upvotes: 0

Burkhard
Burkhard

Reputation: 14738

For costs I would advise against double. Use BigDecimal instead.

As for the formatting:

String.format("%.2d", dcost); and String.format("%.0d", qty); can be used.

Upvotes: 0

pratyoosh kumar
pratyoosh kumar

Reputation: 11

double d;
System.out.printf(".2f",d);

Upvotes: 1

Related Questions