Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

EASY QUESTION: Rounding Integers to 2 decimal places?

Status
Not open for further replies.

clax99

Programmer
Oct 29, 2001
23
US
I have no idea how to round an integer to 2 decimal places. Please help, thanks
 
Integers don't have any decimal places, they are whole numbers.
 
I know, i corrected myself in the very next thread. I obviously mean Double are some other value of greater preciseness.
 
You could do this:

double d = 123.45678;
d *= 100;
long temp = (long) d;
d = temp;
d /= 100;

// d = 123.45

Not exactly simple, but it works.
 
import java.text.DecimalFormat;

public class DFormatTest
{
public static void main(String[] args)
{
double d = 43.335
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
df.setMinimumFractionDigits(2);
df.setDecimalSeparatorAlwaysShown(true);
System.out.println(d);
}
}
 
I have the same question, i posted a thread a little higher before i saw this one. the problem with these solutions is that they trunkate rather than rounding. is there a way around this?
 
DecimalFormat actually uses a rounding method called "half-even" rounding. It is an IEEE standard method of rounding.

You can always do something similar to what was already posted, but add .005 to the number first.

double d = 123.45678;
d+=.005;
d *= 100;
long temp = (long) d;
d = temp;
d /= 100;
 
You can also do this:

double d = 123.45678;
d *= 100;
long temp = Math.round(d);
d = temp;
d /= 100;

This will truncate and round.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top