Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Math.sqrt + rounding up to four decimal places

807600Oct 12 2007 — edited Oct 12 2007
Could someone show me the error of my ways. I have the program doing what I want as far as figuring the square root of even numbers between 0 and 20. My problem is I cant get the numbers to round up and only show four digits after the decimal place. Any help is greatly appreciated.

The results should look like this. (the "=" is there to show empty space)

0 = 0.0000
2 = 1.4142
4 =2.0000
6 =2.4495
8 = 2.8284
10 = 3.1623
12 = 3.4641
14 = 3.7417
16 = 4.0000
18 = 4.2426
20 = 4.4721
 
/ This program finds the even numbers between 0 and 20 and their square root. 
import java.text.*; 

public class SquareRoot { 
  public static void main(String[] args) { 

    // Prints the Table header 
    System.out.println("Number\t\tSquareRoot"); 
    System.out.println("--------------------------"); 


// This part figures the even numbers between 0 and 20 
for (int num = 0; num <= 20; num = num+2) { 


// This prints the number and the square root using the square root method 
DecimalFormat pattern = new DecimalFormat("0.0000";); 
System.out.println(num + "\t\t" + Math.sqrt(num)); 


    } 
  } 
} 
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Nov 9 2007
Added on Oct 12 2007
2 comments
1,114 views