I have an integer that I divide by 100, displaying the result on the screen, from which I can get output like:
91,32
5,22
11,5
I need to always have two decimal places, so I 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 a 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 the sake of clarity, 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
it would not be valid, it would require: 0,40
.
You can use this format:
or also:
this way then you would always get 2 decimal places.
You can use the above in a method:
For example if we define these values:
Using the method you get:
view online demo
As mentioned before, you can use
DecimalFormat
, but it can also be done directly with the classString
.The output I get in both cases is
So I have replaced the comma with a period.
Obtaining the result with a dot instead of a comma.
Try this: