Consider using the
String.format() method. The format string is described in detail in the Formatter API linked to from there. They take a little getting used to, but are quite flexible.
public class FormatterEg {
public static void main(String[] args) {
int[] data = {-5, 0, 1, 42, 666};
for(int test :data) {
System.out.printf("(%3d)%n", test);
}
// once more, with precision...
double[] data2 = {-1, 0, Math.PI, Math.E};
for(double test :data2) {
System.out.printf("(%-8.4f)%n", test);
}
}
}
The first format string means:
( literal left parenthesis
% format
3 three wide
d decimal integer
) literal right parenthesis
%n new line
The second one illustrates how a fixed number of decimal places can be obtained (with correct rounding).
( literal left parenthesis
% format
- left align
8 eight wide
.4 including four decimal places
f floating point number
) literal right parenthesis
%n new line