0

I need program to show only 2 numbers after decimal in answer window. And it shows me a lot more. I have "import java.text.DecimalFormat;" but it doesn't work. Maybe I put it somewhere wrong. Here is my code. How should I make answer to show only 2 number after decimal?

double pb, pc = 0;

    try {
        pb=Double.parseDouble(pakavimoPlotas.getText());
    }
    catch (Exception e) {
      JOptionPane.showMessageDialog(this, "Blogai įvestas pakavimo plotas",
              "ERROR", JOptionPane.ERROR_MESSAGE);  
    }

    pb=Double.parseDouble(pakavimoPlotas.getText());
    pc=pb*0.17;
    pakavimoKaina.setText(""+pc);
    pakavimoKaina2.setText(""+pc+" EUR");
Arminas Šaltenis
  • 166
  • 1
  • 2
  • 10
  • 4
    Possible duplicate of [How to round a number to n decimal places in Java](http://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places-in-java) – Turamarth Dec 20 '16 at 17:09

1 Answers1

0

The post that Turamarth linked will probably solve your problem.

Another solution might be to use BigDecimal (java.math.BigDecimal) for your calculations. I like to use BigDecimal when I am dealing with decimals that I know will need to be scaled or rounded. Here is a small example:

public static void main(String[] args) {            
    BigDecimal bd1 = new BigDecimal("33.34528941");
    BigDecimal bd2 = new BigDecimal("2.98375667");

    BigDecimal bdResult1 = bd1.divide(bd2, 4, RoundingMode.HALF_UP);    
    System.out.println(bdResult1.toString());

    BigDecimal bdResult2 = bd1.multiply(bd2);
    System.out.println(bdResult2.toString());
    bdResult2 = bdResult2.setScale(2, RoundingMode.HALF_UP);
    System.out.println(bdResult2.toString());

    BigDecimal bd3 = new BigDecimal(getSomeDecimalText());
    bd3 = bd3.setScale(2, RoundingMode.HALF_UP);
    System.out.println(bd3.toString());

    double d = bd3.doubleValue();
    System.out.println(d);
}

private static String getSomeDecimalText() {
    return "1.23456789";
}