Gentoo Forums
Gentoo Forums
Gentoo Forums
Quick Search: in
formatting decimals in java
View unanswered posts
View posts from last 24 hours

 
Reply to topic    Gentoo Forums Forum Index Portage & Programming
View previous topic :: View next topic  
Author Message
arachnyd
n00b
n00b


Joined: 03 Jul 2003
Posts: 16

PostPosted: Fri Aug 29, 2003 12:43 am    Post subject: formatting decimals in java Reply with quote

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
View user's profile Send private message
dma
Guru
Guru


Joined: 31 Jan 2003
Posts: 437
Location: Charlotte, NC, USA

PostPosted: Fri Aug 29, 2003 4:02 am    Post subject: Reply with quote

Code:
java.text.DecimalFormat df = new java.text.DecimalFormat("0.00");
System.out.println(df.format(1/3+1/2));
Back to top
View user's profile Send private message
ToucanMan
Tux's lil' helper
Tux's lil' helper


Joined: 28 May 2003
Posts: 97
Location: Montreal, Quebec

PostPosted: Fri Aug 29, 2003 4:11 am    Post subject: Reply with quote

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
View user's profile Send private message
Display posts from previous:   
Reply to topic    Gentoo Forums Forum Index Portage & Programming All times are GMT
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum