Steffan Harris
Steffan Harris

Reputation: 9336

Java output formatting

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.

Upvotes: 4

Views: 4978

Answers (4)

Andy Thomas
Andy Thomas

Reputation: 86509

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.

Upvotes: 10

Bozho
Bozho

Reputation: 597422

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

Upvotes: 4

Peter Lawrey
Peter Lawrey

Reputation: 533890

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);

Upvotes: 1

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285460

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

Upvotes: 2

Related Questions