Reputation: 35
How can I use printf to format spacing AND two decimal places in the same printf?
I can format the spacing using;
System.out.printf("%-20s%-35s%-35s\n", "name : "+shape.getShapeName(),"shape area : "+shape.calculateArea(), "shape perimeter : "+shape.calculatePerimiter());
I can format the two decimal places using;
System.out.printf("Name : "+shape.getShapeName()+" shape area : %.2f shape perimeter : %.2f \n",shape.calculateArea(),shape.calculatePerimiter());
However, I can't work out doing both at the same time, in the same printf.
Here is the minimal reproducible code;
public class StackOverflowCode {
/**
* @param args
*/
public static void main(String[] args) {
String shapeName = "Circle";
double shapeArea = 2.2222222222;
double shapePerimeter = 5.555555;
System.out.printf("%-20s%-35s%-35s\n", "name : "+shapeName,"shape area : "+shapeArea, "shape perimeter : "+shapePerimeter);
System.out.printf("Name : "+shapeName+" shape area : %.2f shape perimeter : %.2f \n",shapeArea,shapePerimeter);
}
}
Upvotes: 0
Views: 284
Reputation:
public class StackOverflowCode {
/**
* @param args
*/
public static void main(String[] args) {
String shapeName = "Circle";
double shapeArea = 2.2222222222;
double shapePerimeter = 5.555555;
System.out.printf("%-20s%-35s%-35s\n", "name : "+shapeName,"shape area : "+shapeArea, "shape perimeter : "+shapePerimeter);
System.out.printf("Name : "+shapeName+" shape area : %.2f shape perimeter : %.2f \n",shapeArea,shapePerimeter);
//spacing and two decimal places in the same printf
System.out.printf( "Name : "+shapeName+"%6s"+" shape area : %.2f %6s shape perimeter : %.2f \n","",shapeArea,"",shapePerimeter);
}
}
Upvotes: 1