Hi, I'm Ataias Reis

Programmer, made in Brazil, Alma mater University of Brasilia

Print double in Java with variable precision

There are some details I never cared about that I started to learn. One of them is just printing to the screen with variable precision. The solution is quite simple.

import java.util.*;

/**
* Prints pi with n decimal places.
* n is given by the user
*/
class Main {
  public static void main(String[] args) {
    double pi = Math.PI;
    Scanner scanner = new Scanner(System.in);
    int precision = scanner.nextInt();
    scanner.close();

    String format = "%." + precision + "f\n";
    System.out.printf(format, pi);
  }
}

The difficulty is just thinking that you can define a string with the precision you want and then use it to print to the screen.

That's all for this post. Thanks for reading!

Tags
comments powered by Disqus