faqts : Computers : Programming : Languages : Java

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

14 of 17 people (82%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

i had a double value a=45.45678, now i need to round it to a=45.46, what method should be used

Sep 19th, 2003 06:55
Cade Mis, anil kumar, www.cademis.com


May be there is an even simpler way than this but it works!
1. Multiply by 100
2. Round the double (Using Math.round)
3. Divide by 100



/**
 * @author cademis
 *
 * To change the template for this generated type comment go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 * 
 * 19.09.2003
 */
public class MathExamples {
	
	
	/**
     * @param in
     * @return
     *  
     * Rounds a double at the second digit after the coma
     */
	public static double roundTwo(double in){		
		return Math.round(in*100.0)/100.0;
	}



	/**
     * @param args
     * 
     * Main to test example methods
     */
    public static void main(String[] args) {
    	
    	double alotOf = 46.34535345345;
    	double onlyTwo = roundTwo(alotOf);
    	
    	System.out.println("Input : " + alotOf);
		System.out.println("Output: " + onlyTwo);
    	
    }
}