0

I want to return a double with 2 decimal places (i.e. 123.00). The following are part of the codes. The output is always 123.0. How to get a two decimal places?

public static double getPrice(){

    double price = Double.valueOf(showInputDialog("Stock's price : "));

    DecimalFormat rounded = new DecimalFormat("###.00");

    double newPrice = Double.valueOf(rounded.format(price));
    System.out.println(newPrice);

    return newPrice;
}
mellissa
  • 87
  • 1
  • 3
  • 13
  • Just FYI, if you're working with currency, you'd better *not* use floating points. – Alvin Wong Mar 17 '13 at 07:43
  • There is such thing as a 'double with two decimal places'. They don't have decimal places at all: they have binary places. If you want decimal places, you must work in a decimal radix, i.e. BigDecimal. – user207421 Mar 17 '13 at 10:48

2 Answers2

3

As long as the return type of your function is double, the short answer is "you can't".

Many numbers that have no more than two decimal digits cannot be represented exactly as double. One common example is 0.1. The double that's nearest to it is 0.100000000000000005551115...

No matter how much rounding you do, you wouldn't be able to get exactly 0.1.

As far as your options go, you could:

  1. accept the rounding issues associated with using double;
  2. return an int (i.e. the rounded value multiplied by 100);
  3. return a String;
  4. return a BigDecimal.

In particular, if you're representing monetary amounts, using double is almost certainly a bad idea.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • so if it's for monetary amounts, which is the best to use? BigDecimal? – mellissa Mar 17 '13 at 07:53
  • @mellissa: http://stackoverflow.com/questions/285680/representing-monetary-values-in-java – NPE Mar 17 '13 at 07:55
  • So, I've tried with bigdecimal and now the trouble is to get two decimal places even when it is a whole number like 123 still prints out 123.00 (with .00 behind). how do I do that? – mellissa Mar 17 '13 at 08:40
1

When formatting, you're making a string from a double. Don't convert your formatted string to a double again :

String formattedPrice = rounded.format(price);
System.out.println(formattedPrice); // prints 123.00 or 123,00, depending on your locale

A double keeps a numerical value following IEEE754, it doesn't keep any formatting information and it's only as precise as the IEEE754 double precision allows. If you need to keep a rendering information like the number of digits after the comma, you need something else, like BigDecimal.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758