If I have the following decimal point numbers:
Double[] numbers = new Double[] {1.1233, 12.4231414, 0.123, 123.3444, 1.1};
for (Double number : numbers) {
System.out.println(String.format("%4.3f", number));
}
Then I get the following output:
1.123
12.423
0.123
123.344
1.100
What I want is:
1.123
12.423
0.123
123.344
1.100
The part that can be a bit confusing is that String.format("4.3", number)
the 4
represents the length of the entire number(including the decimal), not just the part preceding the decimal. The 3
represents the number of decimals.
So to get the format correct with up to 4 numbers before the decimal and 3 decimal places the format needed is actually String.format("%8.3f", number)
.
You can write a function that prints spaces before the number.
If they are all going to be 4.3f
, we can assume that each number will take up to 8 characters, so we can do that:
public static String printDouble(Double number)
{
String numberString = String.format("%4.3f", number);
int empty = 8 - numberString.length();
String emptyString = new String(new char[empty]).replace('\0', ' ');
return (emptyString + numberString);
}
Input:
public static void main(String[] args)
{
System.out.println(printDouble(1.123));
System.out.println(printDouble(12.423));
System.out.println(printDouble(0.123));
System.out.println(printDouble(123.344));
System.out.println(printDouble(1.100));
}
Output:
run:
1,123
12,423
0,123
123,344
1,100
BUILD SUCCESSFUL (total time: 0 seconds)
Here's another simple method, user System.out.printf();
Double[] numbers = new Double[]{1.1233, 12.4231414, 0.123, 123.3444, 1.1};
for (Double number : numbers) {
System.out.printf("%7.3f\n", number);
}