38

Possible Duplicate:
Round a double to 2 significant figures after decimal point

I am trying to format a double to 2 decimal places with leading zeros and there's no luck. Here is my code:

Double price = 32.0;
DecimalFormat decim = new DecimalFormat("#.##");
Double price2 = Double.parseDouble(decim.format(price));

And I want output to be 32.00 instead I get 32.0
Any solutions??

Community
  • 1
  • 1
Bat_Programmer
  • 6,501
  • 9
  • 54
  • 67
  • 2
    Since it looks like you're dealing with currency here, consider using `BigDecimal` to represent money. Using floating-point numbers can lead to rounding problems. – Tyler Treat Oct 20 '10 at 00:22
  • I'm sure there are a million SO threads on currency. I prefer integers to BigDecimal and then I deal in terms of pennies. Of course, that's neither here nor there... – Tony Ennis Oct 20 '10 at 00:30
  • your code isn't quite right (for example you never show how you are getting the output). Could you change your program to a complete working one (with a class and a main method) and tell us the expected output? – TofuBeer Oct 20 '10 at 14:19
  • new DecimalFormat("0.00").format(double-value); – Googlian Oct 31 '18 at 11:24

2 Answers2

60

OP wants leading zeroes. If that's the case, then as per Tofubeer:

    DecimalFormat decim = new DecimalFormat("0.00");

Edit:

Remember, we're talking about formatting numbers here, not the internal representation of the numbers.

    Double price = 32.0;
    DecimalFormat decim = new DecimalFormat("0.00");
    Double price2 = Double.parseDouble(decim.format(price));
    System.out.println(price2);

will print price2 using the default format. If you want to print the formatted representation, print using the format:

    String s = decim.format(price);
    System.out.println("s is '"+s+"'");

In this light, I don't think your parseDouble() is doing what you want, nor can it.

Hardik Mishra
  • 14,479
  • 9
  • 59
  • 96
Tony Ennis
  • 11,565
  • 6
  • 49
  • 71
15

Try this:

 DecimalFormat decim = new DecimalFormat("#.00");
TofuBeer
  • 59,636
  • 18
  • 114
  • 160