I want to print a fractional number into specific length of space with formatting, in Java. But the length will defined while algorithm running, so I can't use straight formatting, such as:
System.out.printf("%8.1f)
For example that lenght "8" will defined somewhere else while code running, how can I configure it to make it automatic depends on code?
CodePudding user response:
Simply build the string with concatenation
int x = 8;
System.out.printf("%" x ".1f\n", 1.123);
CodePudding user response:
Try this, where your formatting is determined by some 'length' defined in the code:
double x = 5.2375484914759291;
int length = 8;
String format = "%." length "f";
System.out.printf(format,x);
//5.23754849 is the output for printf("%.8f",5.2375484914759291)
By concatenating formatting strings to your number variable, you can specify the formatting. Here is an example of formatting the width for an int:
int y = 247;
int width = 8;
String formatWidth ="%0" width "d";
System.out.printf(formatWidth,y);
//00000247 is the output for printf("d",247)
Extending this to format both length and width:
double z = 247.7526;
int length = 2;
int width = 8;
String formatBoth = "%0" width "." length "f";
System.out.printf(formatBoth,z);
//00247.75 is the output for printf(".2f",247.7526)
You could also play around with your formatting string by declaring length and width as String variables, depending on your code.