0

I am looking to print a double to a variable precision, but without rounding. For example:

    Scanner input = new Scanner(System.in);
    double num;
    System.out.println("Enter a double:");
    num = input.nextDouble();
    int precision;
    System.out.println("Enter precision:");
    precision = input.nextInt();

Now I want to print num to the decimal place of precision. Is there a simple way to print this?

EDIT: I have not seen another question answered as to how to use a variable value. The DecimalFormat option rounds the number, which I do not want. Ideally, I am looking for a way to use a variable in:

    "%.nf"

rather than

    "%.3f"
  • The question this is considered a duplicate of does not really answer my question. I attempted to use DecimalFormat and it rounded the number. – user4332594 Sep 02 '15 at 16:10

1 Answers1

1

Use, as a formatted String, "%.nf", where n is replaced by the number of decimal places.

Example:

System.out.printf("%.1f, %.2f\n", 1.234d, 1.234d);
// 1.2, 1.23

See the Javadoc.

To insert a variable into this, just do "%." + intValue + "f".

bcsb1001
  • 2,834
  • 3
  • 24
  • 35