打印 N 位小数的浮点数或双精度数

Print N decimals of float or double

写这样的东西最好的方法是什么:

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

谢谢!

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

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

要保留双精度的小数位数,您可以使用 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));