Reputation: 97
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;
}
Upvotes: 0
Views: 7973
Reputation: 382150
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.
Upvotes: 1
Reputation: 500357
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:
double
;int
(i.e. the rounded value multiplied by 100);String
;BigDecimal
.In particular, if you're representing monetary amounts, using double
is almost certainly a bad idea.
Upvotes: 3