我正在开发一个需要将 long 和 double 格式化为货币的应用程序。我得到了正确的输出,数字出现在我的控制台中,但不是美元格式。 我试过使用 NumberFormat 但它没有用,也许我把它放在了错误的地方。这是我的代码:
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;
}
这告诉我将货币转换为字符串。当我这样做并尝试为 calculateTotalPrice 方法返回货币时,java 告诉我要么:将方法返回类型更改为 String 或将货币类型更改为 double,这两者都会增加更多错误 - 永无止境的循环。
我只想将我的 nightlyRate 和 TotalPrice 更改为货币格式。任何帮助我们都很感激。
根据请求,我将显示准确的错误消息: 当我在 calculateTotalPrice() 中运行这些代码行时:
double currency = NumberFormat.getCurrencyInstance().format(TotalPrice);
return currency;
错误:
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)
当我将货币变量转换为字符串时
String currency = NumberFormat.getCurrencyInstance().format(TotalPrice);
return currency;
我收到完全相同的错误说明:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Type mismatch: cannot convert from String to double
最佳答案
您使用不当。试试这个。
import java.text.*;
public class Currency {
private double TotalPrice;
// only one instance required
NumberFormat nformat = NumberFormat.getCurrencyInstance();
public static void main(String[] args) {
new Currency().start();
}
public void start() {
final double nightlyRate = 100.00;
int elapse = 1020202220; // random value
double elapsedDays = elapse / (24 * 60 * 60 * 1000.);
TotalPrice = elapsedDays * nightlyRate;
String formattedCurrency = formatCurrency(TotalPrice);
System.out.println(formattedCurrency);
}
public String formatCurrency(double amount) {
String fmtedCurrency = nformat.format(amount);
return fmtedCurrency;
}
}
根据您所在的位置,您可能需要也可能不需要设置区域设置。你应该使用美分来处理你的货币单位。稍后转换为美元。 这可能对你有用。 Why not use Double or Float to represent currency?
关于java - 使用 Java 从方法内转换为货币,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55892261/