Main Content

Java - converting an integer to a fixed length string

Archive - Originally posted on "The Horse's Mouth" - 2015-02-04 01:01:13 - Graham Ellis

There are some things in Java which you would think are no-brainers (one-liners) but turn out to be not quite so simple. This issue has improved over the years, with additions of methods like split to java.lang.String, but some gaps remain. And the solution - the joy of an OO langauge - is for you to write a solution that fits you (and your organisation) just one, and then have it as a one-liner as you wanted, but better than that have it tuned to your specific needs.

Converting an integer to a string, fixed width, space padded. Easy with a function call. Here's the call
  expandTo(builder[row][col],6)
and here's the function defintion:
  public static String expandTo(int val, int cols) {
    StringBuffer wip = new StringBuffer(Integer.toString(val));
    while (wip.length() < cols) wip.insert(0," ");
    return wip.toString();
    }


Reading a number from the user. Easy with a function call. Here's the call
  daily[so_far] = WellHouseInput.readNumber();
and you can find the function definition [here]