View previous topic :: View next topic |
Author |
Message |
arachnyd n00b
Joined: 03 Jul 2003 Posts: 16
|
Posted: Fri Aug 29, 2003 12:43 am Post subject: formatting decimals in java |
|
|
Hey,
I need to get this code to format the value of AverageAge accuratly to two decimal places.
public double calculateAverageAge()
{
double averageAge;
averageAge = (myPerson1.getAge() + myPerson2.getAge() +
myPerson3.getAge())/(3.0);
return averageAge;
}
Any ideas? This is for my CS101 class :/ |
|
Back to top |
|
|
dma Guru
Joined: 31 Jan 2003 Posts: 437 Location: Charlotte, NC, USA
|
Posted: Fri Aug 29, 2003 4:02 am Post subject: |
|
|
Code: | java.text.DecimalFormat df = new java.text.DecimalFormat("0.00");
System.out.println(df.format(1/3+1/2)); |
|
|
Back to top |
|
|
ToucanMan Tux's lil' helper
Joined: 28 May 2003 Posts: 97 Location: Montreal, Quebec
|
Posted: Fri Aug 29, 2003 4:11 am Post subject: |
|
|
It's been a while since I wrote anything in java but look into these two classes:
NumberFormat and DecimalFormat. DecimalFormat especially
Example of usage:
Code: | ...
double nonFormattedNum = 3.141592638; // pi (off the top of my head -- If I'm wrong don't hurt me!)
double formattedNum;
DecimalFormat fmt = new DecimalFormat ("0.##");
formattedNum = fmt.format(nonFormattedNum);
System.out.println("pi is (to 2 decimal places): "+formattedNum);
...
/* Output: pi is (to 2 decimal places): 3.14 /* |
Of course you can always design your own method for formatting the number.
FYI: I used the book "Java Software solutions: Foundations of Program Design" by Lewis and Loftus. (It was my first real programming book. It's a good one!)
(EDIT: I forgot to mention that the class can be found in java.text) |
|
Back to top |
|
|
|