Java - toString Formatting (Formatting Doubles) -
the project working on requires bank account balance printed using tostring method. not allowed add methods current program, need format mybalance variable double goes 2 decimal places instead of one. in particular instance program should printing 8.03, printing 8.0.
here tostring method:
public string tostring() { return"savingsaccount[owner: " + myname + ", balance: " + mybalance + ", interest rate: " + myinterestrate + ",\n number of withdrawals month: " + mymonthlywithdrawcount + ", service charges month: " + mymonthlyservicecharges + ", mystatusisactive: " + mystatusisactive + "]"; }
i new java still, know if there way implement %.2f string somewhere format mybalance variable. thank you!
use string.format(...)
this:
@override public string tostring() { return "savingsaccount[owner: " + myname + ", balance: " + string.format("%.2f", mybalance) + ", interest rate: " + string.format("%.2f", myinterestrate) + ",\n number of withdrawals month: " + mymonthlywithdrawcount + ", service charges 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 month: %d, service charges month: %.2f, " + "mystatusisactive: %s]", myname, mybalance, myinterestrate, mymonthlywithdrawcount, mymonthlyservicecharges, mystatusisactive); return result; }
note khelwood asked use of "%n"
new-line token rather usual "\n"
string. use %n
because allow java.util.formatter
platform specific new-line, useful in particular if want write string file. note string.format(...)
system.out.printf(...)
, similar methods use java.util.formatter
in background applies them well.
Comments
Post a Comment