简体   繁体   English

使用Java从方法中转换为货币

[英]Converting to Currency from within a method using Java

I am working on an app that requires long and double to be formatted as currency. 我正在开发一个应用程序,需要long和double才能格式化为货币。 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. 我尝试使用NumberFormat,但它不起作用,也许我把它放在错误的地方。 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. 当我这样做,并尝试返回calculateTotalPrice方法的货币时,java告诉我要么:将方法返回类型更改为String或将货币类型更改为double,这两者都会添加更多错误 - 永远不会结束循环。

All I want to do is change my nightlyRate and TotalPrice to currency format. 我想做的就是将nightlyRate和TotalPrice更改为货币格式。 Any help us appreciated. 任何帮助我们的赞赏。

Per Request I will show exact error messages: When I run these lines of code in the calculateTotalPrice(): 每个请求我将显示确切的错误消息:当我在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时

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

You are using it incorrectly. 您使用不正确。 Try this. 尝试这个。

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

}

And depending where you are, you may or may not need to set the Locale. 根据您的具体情况,您可能需要也可能不需要设置区域设置。 And you should be using cents to handle your monetary units. 你应该用美分来处理你的货币单位。 Convert to dollars later. 稍后转换为美元。 This may be of use to you. 这可能对你有用。 Why not use Double or Float to represent currency? 为什么不使用Double或Float来表示货币?

The format() -method returns a String , so your first approach was pretty good already: format() -method返回一个String ,所以你的第一个方法已经非常好了:

String currency = NumberFormat.getCurrencyInstance().format(TotalPrice);

However, now your method calculateTotalPrice() wants to return a double , so you need to either change the method's return type to String , too, or convert your string back to a double (which I doubt you really want). 但是,现在你的方法calculateTotalPrice()想要返回一个double ,所以你需要将方法的返回类型更改为String ,或者将你的字符串转换回double (我怀疑你真的想要)。 Please note that using double for monetary matters is bad. 请注意,使用double的货币问题是不好的。 You should use BigDecimal instead. 你应该使用BigDecimal

First of all, you should carefully choose the type to use when dealing with finances . 首先,您应该仔细选择处理财务时使用的类型 Floating point numbers WILL have rounding errors. 浮点数将具有舍入误差。 That's why you should use BigDecimal . 这就是你应该使用BigDecimal的原因。

Then, to parse a String to BigDecimal, as suggested here , you should use setParseBigDecimal in DecimalFormat class, then parse will return a BigDecimal for you. 然后,要将String解析为BigDecimal, 如此处所示 ,您应该在DecimalFormat类中使用setParseBigDecimal ,然后parse将为您返回一个BigDecimal。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM