0

In Java, I want to scan user for formatString and inputDouble as follows:

Scanner scan = new Scanner(System.in);
System.out.println("Enter formating string and double to format:");
String formatString = scan.next();
Double inputDouble = scan.nextDouble();

But for now, let's say I only have

String formatString = "%.2f";
Double inputDouble = 42.424242;

I would to use the System.out.printf(); to format the inputDouble based on the formatString. Something like:

System.out.printf("Formated double: '%s'", formatString, inputDouble);

so something in form:

System.out.printf("Formated double: 'magicGoesHere'", formatString, inputDouble);

So in this particular case, I would like to see output:

Formated double: 42.42

Is it possible somehow? thanks

1
  • 1
    String.format(formatString, inputDouble), then use the resulting String in your System.out Commented Nov 4, 2015 at 23:49

2 Answers 2

1
System.out.printf("Formated double: '%s'", String.format (formatString, inputDouble));
Sign up to request clarification or add additional context in comments.

1 Comment

Alternatively: System.out.printf(String.format("Formated double: '%s'", formatString), inputDouble).
1

Split the call up into parts:

System.out.print("Formated double: '");
System.out.printf(formatString, inputDouble);
System.out.print("'");

1 Comment

nice trick, didn't think of it, but I really like it, Thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.