# Need Help Rounding

I need help with a rounding problem. I want to take a number and convert it with two decimal places.

For instance, 345.667 would end up being 345.67; and 345 would end up being 345.00.

I have the following:

double number = Marth.round(number * 100.0)/100.0;

This works for most numbers, but when I have a whole number it converts it 345.0 with only one decimal place.

Any suggestions?
LVL 1
###### Who is Participating?

Commented:
you should have format "#####.00" - see my tested example
0

Commented:

something like that:

DecimalFormat f = new DecimalFormat("#####.##");

double d = 345.6789;
String s = f.format(d);
0

Commented:

This does what you want:

``````        DecimalFormat fff = new DecimalFormat("#####.00");
System.out.println(fff.format(345.6789));
System.out.println(fff.format(365.0));
``````

``````345.68
365.00
``````
0

Commented:
More examples:

`````` DecimalFormat fff = new DecimalFormat("#####.00");
System.out.println(fff.format(345.6789));

System.out.println(fff.format(365.0));

System.out.println(fff.format(365));
``````

Output:

``````345.68
365.00
365.00
``````
0

Author Commented:
Is there no way to keep the number as a double? Without converting to string?
0

Commented:
What you are asking in fact applies to strings - for double number there is no difference between

double d = 365;

double d = 365.0;

double d = 365.00;

those are all the same double - it is hen you want to print them where the difference come.

You of course can say

double d = Double.parseDouble(fff.format(345));

but it does not make much sense - if you could explain in  what context you mmay need it

0

Commented:
your rounding will work in the sense of giving number with no more that two digits

double number = Marth.round(number * 100.0)/100.0;

but when you apply it to number with less decimal digits - I don't see where is the program unless you want to print it
0

Commented:
but when you apply it to number with less decimal digits - I don't see where is the problem unless you want to print it
0

Author Commented:
I'm not getting the decimals to print out correctly.

Here is my function:

``````public String roundTwoDecimals(double number) {
number = Math.round(number * 100.0)/100.0;
DecimalFormat twoDecForm = new DecimalFormat("###############.##");
String dollarAmount = twoDecForm.format(number);
//return Double.valueOf(twoDecForm.format(number));
return dollarAmount;
}
``````

This will work if I have a number like 34.5677, but it still won't work for when I have a number like 64 or 54.6
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.