首页 > 解决方案 > 使用 Java 从方法中转换为货币

问题描述

我正在开发一个需要 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

标签: java

解决方案


您使用不正确。尝试这个。

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;
   }

}

根据您所在的位置,您可能需要也可能不需要设置语言环境。你应该使用美分来处理你的货币单位。稍后兑换成美元。这可能对你有用。为什么不使用 Double 或 Float 来表示货币?


推荐阅读