user2145696
user2145696

Reputation: 23

Formatting currency within a method?

public String toString() //toString withing Shiftsupervisor class
{
    String employee = name + ", " + iD + ", " + hireDate + ", $" + AnnualSal + ", $" + ProdBonus;
    return employee;
}

in main:

ShiftSupervisor supervisor1 = new ShiftSupervisor("John Smith", "123-A", "11-15-2005", 48000, 6500);

System.out.println(supervisor1);

I already added the "$" in my toString but I want this to output the last 2 doubles as 48,000 and 6,500 << adding in the commas!

Could I do this in my setMethods??

Upvotes: 2

Views: 84

Answers (2)

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

Do not reinvent the wheel. Use NumberFormat#getCurrencyInstance that already handles this for you. Here's an example:

NumberFormat cnf = NumberFormat.getCurrencyInstance(Locale.US);
System.out.println(cnf.format(48000)); // prints $48,000.00

If you want to omit the decimal part, just use NumberFormat#setMaximumFractionDigits:

NumberFormat cnf = NumberFormat.getCurrencyInstance(Locale.US);
cnf.setMaximumFractionDigits(0);
System.out.println(cnf.format(48000)); // prints $48,000

Implementing this in your method:

NumberFormat cnf = NumberFormat.getCurrencyInstance(Locale.US);
String employee = name + ", " + iD +
    ", " + hireDate +
    ", " + cnf.format(AnnualSal) +
    ", " + cnf.format(ProdBonus);

Upvotes: 2

Gilbert Le Blanc
Gilbert Le Blanc

Reputation: 51445

Could I do this in my setMethods?

Yes, you can, but you don't want to. Trust me on this one.

Usually, you keep the raw values (int, double, float) in your class, and format them in the get methods. This allows you to format your class output in different ways for different needs.

Upvotes: 1

Related Questions