Rounding a Double

J

Jazz

Hello All I would like to round a double to 2 decimal places...

I have the following two integers:
protected int stackEmptiedCount; //the number of times a stack is Emptied
protected int noOfPlates; //number of Plates

Then I want to display it:
System.out.println("Average stack size before emptying: " +
noOfPlates/stackEmptiedCount + "\n");

Obviously it gets truncated...cause its a integer...any easy way to display
it as say a 2.47...

Thanks

Jazz
 
M

Michael Borgwardt

Jazz said:
Then I want to display it:
System.out.println("Average stack size before emptying: " +
noOfPlates/stackEmptiedCount + "\n");

Obviously it gets truncated...cause its a integer...any easy way to display
it as say a 2.47...

To do a double division, cast one of the arguments to double.
To display only two decimal places, use java.text.DecimalFormat
 
?

=?ISO-8859-1?Q?=D2scar_P=E9rez_del_Campo?=

Simply do as follows:

java.text.NumberFormat nf;
nf = NumberFormat.getInstance();
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
System.out.println("bla bla bla:
"+nf.format(((double)noOfPlates)/((ddouble)stackEmptiedCount)));
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,995
Messages
2,570,226
Members
46,815
Latest member
treekmostly22

Latest Threads

Top