2015-10-26 14 views
-1

什么是写这样的事情最好的办法:打印传单N浮动小数或双

Scanner input = new Scanner(System.in); 
int n = input.nextInt(); 
double d = 5.123456789123456789; 
System.out.printf("%.nf", d); 

谢谢!

+1

你想要做什么?你想打印双倍n次? –

+0

查看NumberFormat和DecimalFormat – ControlAltDel

回答

2

格式字符串只是您可以在运行时创建的String。例如。

System.out.printf("%." + n + "f", d); 
0

要保留double的小数位数,可以使用java DecimalFormat。

由于只有在运行时才知道小数位数,所以您还需要在运行时为DecimalFormat生成模式。

所以:

int n = 5; // or read in from user input 
    String decimalFormatPattern = "."; 
    for (int i =0 ; i < n; ++i) { // generate pattern at runtime 
     decimalFormatPattern += "#"; 
    } 
    // format pattern would be .##### 
    DecimalFormat decimalFormat = new DecimalFormat(decimalFormatPattern); 

    double d = 5.123456789123456789; 
    System.out.println(decimalFormat.format(d));