Currency output unsing number format class in java

I'm not sure how to use the number format class in order to have a double format into US currency,.

For example if tuition is 1000 ,I would need it to print out $1,000.00 .I will put a piece of code in to show where my trouble is.

The public double getCurrencyInstance() is the method that I started with and it's obviously incorrect.

import java.text.NumberFormat;

public class OnlineStudent extends Student {

    private double computingFee;

    public double getCurrencyInstance(){                
        return computingFee;                
    }

    public OnlineStudent(){                
        super();               
    }

    public OnlineStudent(String fName, String lName, String id,  int credits, double rate, double compFee){
        super(fName, lName, id, credits, rate);
        this.computingFee = compFee;
    }

    public void computeTuition(){
        tuition = (rate + computingFee) * creditNum;
    }

    public String toString(){
        return ("\nOnline Student:\nFirst name:\t\t" + firstName + "\nLast name:\t\t" + lastName + "\nStudent ID:\t\t" + studentID 
                + "\nCredits:\t\t" + creditNum + "\nRate:\t\t\t" + super.rate + "\nTuition:\t\t" + super.tuition + "\nComputing Fee:\t\t"
                + getCurrencyInstance() + "\n\n");

    }
}
Jon Skeet
people
quotationmark

You need to use NumberFormat.getCurrencyInstance(...), and then use that to format your value. For example:

public String toString() {
    NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(Locale.US);
    return "\nOnline Student:\nFirst name:\t\t" + firstName 
         + "\nLast name:\t\t" + lastName + "\nStudent ID:\t\t" + studentID 
         + "\nCredits:\t\t" + creditNum 
         + "\nRate:\t\t\t" + currencyFormat.format(super.rate)
         + "\nTuition:\t\t" + currencyFormat.format(super.tuition) 
         + "\nComputing Fee:\t\t" + currencyFormat.format(computingFee) + "\n\n");
}

I'd strongly advise you to use BigDecimal for currency values though, instead of double. I'd also reconsider computeTuition to return the tuition fee rather than just storing it in a field, but that's a different matter.

people

See more on this question at Stackoverflow