Take the 2-minute tour ×

I implemented a counter method that returns always an incremented number. But the user can give wished format, 2 digits, 3 digits or whatever he wants. The format is the standard String.format() type of String like %02d or %5d. When the maximum value is reached, the counter should be reset to 0.

How can I find out the max value that can be represented with the given format?

int counter = 0;
private String getCounter(String format){
    if(counter >= getMaximum(format)){
        counter = 0;
    else {
    return String.format(format, counter);

private int getMaximum(String format){
    //TODO ???
    //Format can be %02d => should return 100
    //Format can be %05d => should return 100000

share|improve this question
add comment

3 Answers

Haven't validated this code, but something along the lines of this should work with erro checking in place

    String str = fullresultText.replace ("%", "").replace("d", "");
    maxVal = Math.pow (10, Integer.parseInt (str));
share|improve this answer
This should work, but will it be compatible with other format expressions too? docs.oracle.com/javase/6/docs/api/java/util/… –  FiveO Oct 1 '13 at 9:16
For my case this is maybe the fastest and easiest way. Just got a problem if other characters are mentioned in the format –  FiveO Oct 1 '13 at 9:19
Thanks, I thought that we were talking about integers, hence the masks of %02d etc. Please accept my answer. –  user2310289 Oct 2 '13 at 0:20
add comment

There is nothing builtin for this, and I'm not aware of any libraries that do this (I could be wrong). You will probably have to parse the format specification and figure it out. Remember that formats will expand if necessary to avoid losing digits. For example

System.out.printf("%06d", 11434235);

will happily print the entire 8-digit number.

share|improve this answer
+1 for warning about the expansion –  Black Panther Oct 1 '13 at 8:21
Well that's my point, when %03d is given, 999 returns 999, 1000 returns 1000, but I only want 3 digits. –  FiveO Oct 1 '13 at 9:15
You want to throw away data? For %03d what do you want to display for value 1234? 123? 234? –  Jim Garrison Oct 1 '13 at 16:22
add comment
private int counter = 0;

private String getCounter(String format) {
    counter = (counter + 1) % getMaximum(format);
    return String.format(format, counter);

private int getMaximum(String format) {
    try {
        MessageFormat messageFormat = new MessageFormat("%{0,number,integer}d");
        int pow = ((Long) messageFormat.parse(format)[0]).intValue();
        return (int) Math.pow(10, pow);
    } catch (ParseException e) {
        System.out.println("Incorrect format");
        return -1;
share|improve this answer
add comment

Your Answer


