| Home | Links |

Rounding

  • It is a method that allows you to round doubles
  • Copy and paste the code below into your class
  • Usually placed a the bottom of the class because then it won’t get in the way of your coding


public class Round
{

public static void main (String args[])
{

new Round ();

}

public Round ()
{

System.out.println (“The volume is “+ round (volume, 2) + “.”);
//the round method is called here
//notice the format used is round(VariableName, number of decimal places)

System.out.println (“The surface area is “+ round (SA, 0) + “.”);
//in this case, there would be no decimal places

}

public double round (double num, int digit)
//when calling the method, use the name declared here
{
    double num2 = num * Math.pow (10, digit);
    double num3 = (num2 - ((int) num2)) * 10;
    num2 = ((int) num2);
    if (num3 >= 5)
    num2++;
    return num2 /= Math.pow (10, digit);
}

}