How to give user the ability to set the decimal format rounding to whichever s/he prefers.

I know that the users input can be gained by the code

``````double decimalRoundTo;
Scanner input = new Scanner(System.in);
out.print(" Enter the number of decimal places you want to round to ");
decimalRoundTo = input.nextDouble();
``````

and the programmer can set the decimal format with the code below.

``````out.format("%.2f", numberToBeRounded);
``````

However, I want to give my user that ability. How would this be possible, if it is at all?

"%.2f" controls the format, but it's just an ordinary string. You could (eg) prompt the user for the number of decimals and use that to construct the string with his number instead of the "2"

OK I was able to solve this challenge. (The code I wrote below works well for me.) Thanks for the idea JamesCherrill.

``````String formatX, decimalRoundToX, formatY, decimalRoundToY;

out.print(" Enter the number of decimal places you want to round x coordinate to ");
decimalRoundToX = input.next();
out.print(" Enter the number of decimal places you want to round y coordinate to ");
decimalRoundToY = input.next();

formatX = ("%."+ decimalRoundToX +"f");
formatY = ("%."+ decimalRoundToY +"f");

out.print(" (");
out.format(formatX, xcor);
out.print(", ");
out.format(formatY, ycor);
out.print(")" + '\n');
``````

Is it okay that I have so many lines of code to dislplay a single line:

``````out.print(" (");
out.format(formatX, xcor);
out.print(", ");
out.format(formatY, ycor);
out.print(")" + '\n');
``````

Or could those lines be cut down to a single line?

You can use out.printf to format multiple items in one line of code, but it's OK to have multiple lines. You should use whichever makes ypur program easier to read and understand.

I've tried to combine all those 5 lines together into one:

``````out.printf(" (" + formatX, xcor + ", " + formatY, ycor + ")" + '\n');
``````

But this didn't make the program work. How is this line wrong? And how will I fix it?