简体   繁体   中英

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. 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

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?

The format() -method returns a String , so your first approach was pretty good already:

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). Please note that using double for monetary matters is bad. You should use BigDecimal instead.

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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