0

The project I am working on requires a bank account balance to be printed using a toString method. I am not allowed to add any methods to my current program, but I need to format my myBalance variable to a double that goes to two decimal places instead of one. In this particular instance my program should be printing 8.03, but it is printing 8.0.

Here is my toString method:

   public String toString()
   {
      return"SavingsAccount[owner: " + myName + 
      ", balance: " + myBalance + 
      ", interest rate: " + myInterestRate + 
      ",\n number of withdrawals this month: " + myMonthlyWithdrawCount + 
      ", service charges for this month: " + 
      myMonthlyServiceCharges + ", myStatusIsActive: " +
      myStatusIsActive + "]";
   }

I am very new to Java still, so I would like to know if there is a way to implement %.2f into the string somewhere to format only the myBalance variable. Thank you!

Trafton
  • 155
  • 1
  • 9

2 Answers2

1

Use String.format(...) for this:

@Override
public String toString() {
    return "SavingsAccount[owner: " + myName + 
    ", balance: " + String.format("%.2f", myBalance) + 
    ", interest rate: " + String.format("%.2f", myInterestRate) + 
    ",\n number of withdrawals this month: " + myMonthlyWithdrawCount + 
    ", service charges for this month: " + 
    myMonthlyServiceCharges + ", myStatusIsActive: " +
    myStatusIsActive + "]";
}

or more succinctly:

@Override
public String toString() {
    String result = String.format("[owner: %s, balance: %.2f, interest rate: %.2f%n" +
        "number of withdrawals this month: %d, service charges for this month: %.2f, " + 
        "myStatusIsActive: %s]",
        myName, myBalance, myInterestRate, myMonthlyWithdrawCount, 
        myMonthlyServiceCharges, myStatusIsActive);
    return result;
}

Note that khelwood asked about my use of "%n" for a new-line token rather than the usual "\n" String. I use %n because this will allow the java.util.Formatter to get a platform specific new-line, useful in particular if I want to write the String to a file. Note that String.format(...) as well as System.out.printf(...) and similar methods use java.util.Formatter in the background so this applies to them as well.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
0

Use String.format()

Example :

Double value = 8.030989;
System.out.println(String.format("%.2f", value));

Output : 8.03

digidude
  • 289
  • 1
  • 8
  • possible duplicate of [link](http://stackoverflow.com/questions/4885254/string-format-to-format-double-in-java) – digidude Jul 21 '15 at 20:56