Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Only 2 decimal places!!!!

 
joe kane
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was wondering how do you, when returning a value that can have loads of decimal places how would you stop it at only two decimal places..
Thanks in advance joe kane
 
Billybob Marshall
Ranch Hand
Posts: 202
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See the javadocs for this class
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I wrote an article about floating point numbers that shows some example of formatting decimals:
http://www.javaranch.com/newsletter/July2003/newsletterjuly2003.jsp#a4
 
joe kane
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the help, but im very new to java and im not too sure where the code goes for the decimal format...?

Here is the program I have, it works 100%, it just needs the decimal format on 3 numbers,
Thanks loads in advance if you can help.....
Thanks joe Kane
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is a simple program that shows how to format a float into a String with two deciamls:

import java.text.*;
public class JunkTest {

public static void main(String [] args) {
float f = 45.67f * 43.15f;
System.out.println(new DecimalFormat("0.00").format(f));
}
}

Notice that we need to import java.text as that is the package that the DecimalFormat class is in.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic