4

I was wondering if Java has some sort of class to help on output formatting. I know in C++, in iomanip, there is a method call setw. I was wondering if Java has something similar to this.

1
  • What output are you trying to achieve? Is this a console program or a GUI program and if the latter, what GUI library are you using? Commented Dec 11, 2010 at 17:16

4 Answers 4

10

Have a look at java.util.Formatter.

String.format() provides a convenient wrapper.

For example (modified from an example on the link):

   String s = String.format("e = %+10.4f", Math.E);

It goes beyond C's ?printf formats. For example, it supports an optional locale, and format symbols can be associated with an argument by explicit index rather than implicit.

Edit: Fixed the link above.

Sign up to request clarification or add additional context in comments.

Comments

4

String.format(..) and possibly java.text.*

Comments

2

There's the Formatter class and its variants: String.format, PrintStream.printf.

Comments

1

The simplest approach is to use printf() which works much the same as printf() in C.

double pi = Math.PI;
System.out.printf ("pi = %5.3f%n", pi);

Comments

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.