Formatting a double in java

5

I would like to know how to keep the variable double with 2 houses after the comma. Below I have an example, when transforming a String into double if it has values after the point is kept the 2 houses, however if it is only zeros, no.

"10.01" => 10.01
"10.00" => 10.0  //Gostaria do resultado 10.00
    
asked by anonymous 28.08.2014 / 20:16

2 answers

14

You can do this:

String resultado = String.format("%.2f", valor);

Or you can also do this:

double numero= 10.00;
DecimalFormat formato = new DecimalFormat("#.##");      
numero = Double.valueOf(formato.format(numero));
    
28.08.2014 / 20:31
2

Also use .setscale()

BigDecimal bd = new BigDecimal(< tipo >);

bd.setscale(< qtdCasas >);
    
18.10.2016 / 23:00