programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Jeanne Boyarsky
• Ron McLeod
• Paul Clapham
• Liutauras Vilda
Sheriffs:
• paul wheaton
• Rob Spoor
• Devaka Cooray
Saloon Keepers:
• Stephan van Hulst
• Tim Holloway
• Carey Brown
• Frits Walraven
• Tim Moores
Bartenders:
• Mikalai Zaikin

# Only 2 decimal places!!!!

Greenhorn
Posts: 29
• Number of slices to send:
Optional 'thank-you' note:
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..

Ranch Hand
Posts: 202
• Number of slices to send:
Optional 'thank-you' note:
See the javadocs for this class

mister krabs
Posts: 13974
• Number of slices to send:
Optional 'thank-you' note:
I wrote an article about floating point numbers that shows some example of formatting decimals:

joe kane
Greenhorn
Posts: 29
• Number of slices to send:
Optional 'thank-you' note:
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 joe Kane

Thomas Paul
mister krabs
Posts: 13974
• Number of slices to send:
Optional 'thank-you' note:
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.