# java – Show number with two decimal places

## Question:

I have an integer that I divide by 100, showing the result on the screen, from which I can get outputs like:

``````91,32
5,22
11,5
``````

I need to always have two decimal places, therefore fill with zeros in case I only have 1, to obtain for example:

``````91,32
5,22
11,50
``````

To get the decimals I convert the initial integer to float, that is, I am doing something like this:

``````int i = 150;
float res, f = (float) i;
res = f / 100;

System.out.println( res );
``````

Edited: For your understanding, I'm going to use it in a program that shows output like this:

``````Contenido total: 126,59€
Hay 49 monedas de 1 cent. Con un valor de: 0,49€
Hay 45 monedas de 2 cent. Con un valor de: 0,90€
Hay 10 monedas de 5 cent. Con un valor de: 0,50€
Hay 14 monedas de 10 cent. Con un valor de: 1,40€
Hay 39 monedas de 20 cent. Con un valor de: 7,80€
Hay 13 monedas de 50 cent. Con un valor de: 6,50€
Hay 27 monedas de 100 cent. Con un valor de: 27,00€
Hay 41 monedas de 200 cent. Con un valor de: 82,00€
``````

Although I had not included it in the question originally, the integer part is also required, even if it has the value 0, that is `,40` would not be valid, it would require: `0,40` .

You can use this format:

`````` DecimalFormat df = new DecimalFormat("#.00");
``````

or also:

``````DecimalFormat df = new DecimalFormat("0.00"); :
``````

in this way then you would always get 2 decimal places.

You can use the above in a method:

``````   private static String getTwoDecimals(double value){
DecimalFormat df = new DecimalFormat("0.00");
return df.format(value);
}
``````

For example if we define these values:

``````91.32
5.22
11.5
1.2
2.6
``````

Using the method you get:

``````91.32
5.22
11.50
1.20
2.60
``````

see demo online.

Scroll to Top