public class Test
{
int i;
Test(int i)
{
this.i=i;
String s=String.valueOf(Math.PI);
System.out.println(s.substring(0,i+2));
}
public static void main(String[] args)
{
new Test(5);
}
/*
* Created on 2004-11-26
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
/**
* @author Hanbing
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class PI {
public String getPI(int n){
String str = null;
String pattern = "###############################################";
DecimalFormat df = new DecimalFormat("0." + pattern.substring(0,n));
double pi = Math.PI;
str = df.format(pi);
return str;
}
public static void main(String[] args) {
System.out.println("Please enter a number:");
int n = 0;
try {
String strN=new BufferedReader(new InputStreamReader(System.in)).readLine();
n = Integer.parseInt(strN);
} catch (Exception e) {
System.out.print("您输入的位数不正确!");
System.exit(0);
}
PI pi = new PI();
System.out.println("默认的PI:" + Math.PI);
System.out.println("精确" + n + "位:" + pi.getPI(n));
}
}
===============
Please enter a number:
10
默认的PI:3.141592653589793
精确10位:3.1415926536