Adelmar
Adelmar

Reputation: 2091

How to format Java String with multiple padded segments

I have some code that assumes an input will not exceed 6 digits. It takes that value, pads it with leading 0's, and then prefixes it with "999", like so:

String.format("999%06d", 123); // => "999000123"

The expected input is now overflowing that 6-digit maximum, into the 7 digits. This produces formatted output of 10 characters (e.g. String.format("999%06d", 1000000); // => "9991000000"), which breaks things for us.

Question: Is it possible to specify this string format so that it will maintain identical logic as above, but instead of always prefixing with leading "999", it will only prefix with TWO leading "9"s if the input is 7 digits long (while still prefixing with THREE leading "9"s if the input is <= 6 digits long)?

To help illustrate, these are the inputs/outputs we would desire when the value increments from 6 to 7 digits:

(Input) => (Formatted Output)
1       => "999000001"
999999  => "999999999"
1000000 => "991000000"

(I know there are other ways to accomplish this, and those are helpful, but our situation is atypical so I'm asking if this can be done in a single String.format call)

Upvotes: 3

Views: 67

Answers (2)

Adam Siemion
Adam Siemion

Reputation: 16029

Workaround

public static String format(int i) {
    String s = String.format("999%06d", i);
    return s.substring(s.length() - 9);
}

Upvotes: 1

Andreas
Andreas

Reputation: 159086

Workaround:

static String prefix999(int number) {
    String s = String.format("999%06d", number);
    return s.substring(Math.min(3, s.length() - 9));
}

Tests

System.out.println(prefix999(123));
System.out.println(prefix999(1));
System.out.println(prefix999(999999));
System.out.println(prefix999(1000000));
System.out.println(prefix999(1234567));
System.out.println(prefix999(12345678));
System.out.println(prefix999(123456789));
System.out.println(prefix999(1234567890));

Output

999000123
999000001
999999999
991000000
991234567
912345678
123456789
1234567890

Upvotes: 1

Related Questions