d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Printing To 2 Decimal Places Using Tostring > How?
Add Reply New Topic New Poll
Member
Posts: 7,510
Joined: Dec 27 2009
Gold: 75.00
Mar 15 2015 07:18pm
How to do this?? :<

public String toString(){

return "\nAccount ID: "+acct_id+"\nBalance:$ "+balance+"\nAccount Owner "+owner.toString();

}

can i alter something there to make it print to 2 d.p?
Member
Posts: 32,925
Joined: Jul 23 2006
Gold: 3,804.50
Member
Posts: 2,757
Joined: Nov 26 2007
Gold: 1,214.81
Mar 16 2015 07:06am
you can also use NumberFormat.getCurrencyInstance() for formatting currency


Code
...
NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
return "\nAccount ID: "+acct_id+"\nBalance: "+currencyFormat.format(balance)+"\nAccount Owner "+owner.toString();
Member
Posts: 5,167
Joined: Nov 23 2006
Gold: 11.01
Mar 16 2015 05:53pm
Look up DecimalFormat object. It should look like this (don't forget to import decimal format class at top):


Code
DecimalFormat df = new DecimalFormat("0.00");

double myNum = 5.5555555555;
System.out.println(df.format(myNum));


This will print out 5.55 but you can change it to 0.000 passing in to decimalformat to change how many decimal places you want.


You then have to override the toString method and print out just your number. Do not forget to use @Override annotation as it helps the compiler.

Code
@Override
public String toString(){

return "\nAccount ID: "+acct_id+"\nBalance:$ "+balance+"\nAccount Owner "+ df.format(myNum);

}


Assuming Owner is the one you want to format. I changed owner.toString to the decimal formatting of myNum which i used in the example above.



Member
Posts: 7,510
Joined: Dec 27 2009
Gold: 75.00
Mar 16 2015 10:16pm
Quote (HoneyBadger @ Mar 16 2015 07:53pm)
Look up DecimalFormat object. It should look like this (don't forget to import decimal format class at top):


Code
DecimalFormat df = new DecimalFormat("0.00");

double myNum = 5.5555555555;
System.out.println(df.format(myNum));


This will print out 5.55 but you can change it to 0.000 passing in to decimalformat to change how many decimal places you want.


You then have to override the toString method and print out just your number. Do not forget to use @Override annotation as it helps the compiler.

Code
@Override
public String toString(){

return "\nAccount ID: "+acct_id+"\nBalance:$ "+balance+"\nAccount Owner "+ df.format(myNum);

}


Assuming Owner is the one you want to format. I changed owner.toString to the decimal formatting of myNum which i used in the example above.


thanks man, got it :D
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll