Formatting a double in java

Asked

Viewed 57,495 times

7

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 in 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
  • 2

    You want to format the double back to a String with the correct two decimal places? The internal format of the double is fixed, however, for display issues it is possible to format yes.

2 answers

18


You can do it like this:

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

Or you can do it like this:

double numero= 10.00;
DecimalFormat formato = new DecimalFormat("#.##");      
numero = Double.valueOf(formato.format(numero));

4

Also use the .setscale()

BigDecimal bd = new BigDecimal(< tipo >);

bd.setscale(< qtdCasas >);
  • But then it stops being double. From what I understand, it’s to transform a String in double without losing the decimals.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.