1

I am writing a program and am stuck in the following requirement:

The output goes to a fixed format file

     Total 1                   Total 2
 ----------------          ----------------
       311,862.33                 23,456.00
        40,000.00                789,123.00  

As in above example, the length of the amount string varies.

Requirement is that the amount should always start at the end of the 'hyphens'.

How to achieve this ?

I know that right and left pad to the string could be acheived through:

String.format("%1$#20s", "311,862.33");
String.format("%1$-15s", "12345");

But how to achieve in my case where there are multiple strings in every line and the string lengths are dynamic ?

Found below code which formats amount in a single column. But how to achieve the same for multiple columns i.e. multiple amounts in same line ?

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);
}

This will give output as:

123.45
 99.00
 23.20
 45.00

Thanks for reading!

3 Answers 3

1

I would use a StringBuilder and put in the padding myself by tracking row length in a counter.

It's not the fastest or concise method, but it does provide better readability and transparency. The JIT is likely to optimise this sort of instruction if the code path is hot.

Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

   try {
       String formatCol1 = "%10.2f"; // width == 10 and 2 digits after the dot
       String formatCol2 = "%15.2f"; // adjust width to control space between columns

       float[] floats1 = {123.45f, 99.0f, 23.2f, 45.0f};
       float[] floats2 = {12345.67f, 999.90f, 2345.32f, 12.0f};
       for (int i=0; i<floats1.length; i++) {
           float value1 = floats1[i];
           float value2 = floats2[i];

           ByteArrayOutputStream baos = new ByteArrayOutputStream();
           PrintStream printStream = new PrintStream(baos);
           printStream.format(formatCol1, value1);
           printStream.format(formatCol2, value2);

           System.out.println(baos.toString("utf8"));
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

Output is:

123.45       12345.67
 99.00         999.90
 23.20        2345.32
 45.00          12.00

Comments

0

It could be easily done using string format method:

String amount1 = "311,862.33";
String amount2 = "45,678.22";
String content = String.format("%26s", amount1) + String.format("%20s", amount2);

This will give output exactly how I want.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.