Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.2k views
in Technique[技术] by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...