Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/svg/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 打印浮点或双精度的N个小数_Java_Decimal Point - Fatal编程技术网

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

Java 打印浮点或双精度的N个小数,java,decimal-point,Java,Decimal Point,写这样的东西最好的方法是什么: Scanner input = new Scanner(System.in); int n = input.nextInt(); double d = 5.123456789123456789; System.out.printf("%.nf", d); 谢谢 格式字符串只是一个可以在运行时创建的字符串。例如 System.out.printf("%." + n + "f", d); 要保留双精度小数位数,可以使用java DecimalFormat 因为只有

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

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

谢谢

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

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

要保留双精度小数位数,可以使用java DecimalFormat

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

因此:


你想做什么?要打印双d n次吗?请检查NumberFormat和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));