Formatting numbers with same amount of padding
java
Solution
Try with `String.format()` (JavaDoc):
public static void main(String args[]){
String format = "%10.2f\n"; // width == 10 and 2 digits after the dot
float [] floats = {123.45f, 99.0f, 23.2f, 45.0f};
for(int i=0; i<floats.length; i++) {
float value = floats[i];
System.out.format(format, value);
}
and the output is :
123.45
99.00
23.20
45.00
Problem
I want to format 3 digit floats in Java so they line up vertically such that they look like: ``` 123.45 99 23.2 45 ``` When I use DecimalFormat class, I get close, but I want to insert spaces when the item has 1 or 2 digits. My code: ``` DecimalFormat formatter = new java.text.DecimalFormat("####.##"); float [] floats = [123.45, 99.0, 23.2, 45.0]; for(int i=0; i<floats.length; i++) { float value = floats[i]; println(formatter.format(value)); } ``` It produces: ``` 123.45 99 23.2 45 ``` How can I print it so that all but the first line is shifted over by 1 space?