I am working on an app that requires long and double to be formatted as currency. I am getting the correct output and the numbers appear in my console but not in dollar format. I have tried using the NumberFormat but it did not work, maybe I am placing it in the wrong place. Here is my code:
import java.text.DateFormat;
import java.util.Date;
import java.text.NumberFormat;
private Date arrivalDate;
private Date departureDate;
private long elapsedDays;
private double TotalPrice;
public static final double nightlyRate = 100.00;
public double calculateTotalPrice()
{
long arrivalDateTime = arrivalDate.getTime();
long departureDateTime = departureDate.getTime();
long elapse = departureDateTime-arrivalDateTime;
elapsedDays = elapse/(24*60*60*1000);
TotalPrice = elapsedDays * nightlyRate;
NumberFormat currency = NumberFormat.getCurrencyInstance().format(TotalPrice);
return TotalPrice;
}
public double getTotalPrice()
{
this.calculateTotalPrice();
return TotalPrice;
}
This tells me to convert currency to a string. When I do that, and try to return currency for the calculateTotalPrice method, java tells me to either: change the method return type to String or change type of currency to double, both of which add more errors - never ending loop.
All I want to do is change my nightlyRate and TotalPrice to currency format. Any help us appreciated.
Per Request I will show exact error messages: When I run these lines of code in the calculateTotalPrice():
double currency = NumberFormat.getCurrencyInstance().format(TotalPrice);
return currency;
ERROR:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Type mismatch: cannot convert from String to double
at
calculate.reservation.totals.Reservation.calculateTotalPrice(Reservation.java:48)
at calculate.reservation.totals.Reservation.getTotalPrice(Reservation.java:54)
at calculate.reservation.totals.CalculateReservationTotals.main(CalculateReservationTotals.java:63)
When I do convert the currency variable to a String
String currency = NumberFormat.getCurrencyInstance().format(TotalPrice);
return currency;
I get the exact same error stating:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Type mismatch: cannot convert from String to double