Java only 2 decimal places [duplicated]

0

I have this code, where I do the sum of a column of a jtable, but I have a problem, I want to limit the number of decimals that come out but I did not get it. Try with the DecimalFormat, but I run it and it does not add anything, it comes out as result 0, of a column that does have data. Any suggestions or help?

txtSuma.setText("0");
int ta=jReporteGanadores.getRowCount();
int c=0;
do
    try {
        int f=c++;
        double n1=Double.parseDouble(jReporteGanadores.getValueAt(f,5).toString());
        String nu=txtSuma.getText();
        double nu2=Double.parseDouble(nu);
        double n2=Double.parseDouble(txtSuma.getText());
        double re=n1+nu2;//LUGAR A FORMATEAR DECIMALES
        String df=String.valueOf(re);
        int cd=df.indexOf(".");
        String x=df.substring(cd+2);
        if(x.isEmpty()){
            txtSuma.setText(String.valueOf(re+"0"));
        }else{
            String vx=txtSuma.getText();
            double vx2=Double.parseDouble(vx);
            double ref=(double) n1+vx2;
            txtSuma.setText(String.valueOf(ref));
        }    
    }catch(Exception e){
    }
while(c<ta);
    
asked by user83962 13.08.2018 в 22:17
source

2 answers

1

You should only use the DecimalFormat after doing the addition:

DecimalFormat df = new DecimalFormat("#.00");
double resultado = c1+c2;
df.format(resultado);

Or you can use it like this:

double valorfinal = Math.round(resulado*100d)/100d;
    
answered by 13.08.2018 в 22:45
0

To limit to only 2 decimals in case of being a double variable you must do the following:

double R=83.13532213;

   R=Math.round(R*100.0)/100.0;
   System.out.print(R);//83.14

So I recommend that you output the stores in a single double variable and apply Match.round as I did before.

    
answered by 13.08.2018 в 22:46