1

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
CodeConnoisseur
  • 1,452
  • 4
  • 21
  • 49

3 Answers3

2

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?

WJS
  • 36,363
  • 4
  • 24
  • 39
  • Hi, WJS, I imported your code and also imported the java.util.Locale. In my code I try to do this: return nformat; But I get the red underline under nformat when trying to return it. IDE suggestion is 1. Change the method return type to number format or 2. change type of nformat to double. – CodeConnoisseur Apr 28 '19 at 16:53
  • You want to return a string of the formatted number, not the format itself, don't you? So the return type needs to be string, not double. In my example you want to return output. – WJS Apr 28 '19 at 17:01
  • I have this code: NumberFormat nformat = NumberFormat.getCurrencyInstance(Locale.US); String output = nformat.format(TotalPrice); return output; It still returns the total price like this: 345.0 or 115.0 etc. I need it t have the $ – CodeConnoisseur Apr 28 '19 at 17:04
  • I'm editing my example so you can see it in its entirety. – WJS Apr 28 '19 at 17:08
  • sweet this worked, now my TotalPrice is outputted as currency. The last thing is, how do I get my nightlyRate to be outputted as currency? – CodeConnoisseur Apr 28 '19 at 17:19
  • Your nightly rate is a fixed constant so it can be formatted when it's declared. In my example you would just pass it to the formatting method and use the output. But you have to organize your code so you only format it when it is time to display it. – WJS Apr 28 '19 at 17:23
  • 2
    I am sorry to say, but with a background of three years programming you should be able to spot what to do with WJS example: `formattedCurrency = formatCurrency(nightlyRate); System.out.println(formattedCurrency);` – moxim Apr 28 '19 at 17:23
1

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.

moxim
  • 111
  • 1
  • 9
0

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.

Leonardo Alves Machado
  • 2,747
  • 10
  • 38
  • 53
  • I honestly do not see the point to use BigDecimal for some homework type of code and the mathematical requirements here could clearly be handled with long and double without getting any rounding errors. Look at the code, something about number of hotel nights that should be multiplied with the nightly rate, hardly high fincance. And you don't really supply an answer to OP's issue apart from some link. – Joakim Danielson Apr 28 '19 at 17:07
  • If you do things the wrong way in your homework, you will probably do the same in your job. And it is not harder to do it the right way... – Leonardo Alves Machado Apr 28 '19 at 17:12
  • 1
    See my updated comment. This has nothing to do with finance, it's some basic math where the focus is on properly formatting a number. Ever heard of "right tool for the job"? – Joakim Danielson Apr 28 '19 at 17:14
  • 1
    I definitely agree with Leonardo. And BigDecimal *is* the right tool for the job. See WLS excellent link. – moxim Apr 28 '19 at 17:25
  • @moxim multiplying 100.0 with a integer that is most likely single or possibly double digit requires BigDecimal in your opinion? Don't make this into something it isn't. – Joakim Danielson Apr 29 '19 at 05:57