Search code examples
javadecimal-point

Print N decimals of float or double


What is the best way to write something like this:

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

Thanks!


Solution

  • The format string is just a String that you can create at runtime. E.g.

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