-3

Still i am getting file name like below:

B-13-4-006.jpg

and

B-5-7-008.jpg

but now i want to show 0 as prefix if value less than < 9 else as it is, in short want to show values in double figures, see my code below using to file name

               "B-" + // prefix
                LoginActivity.strEventID + "-" + // eventID 
                LoginActivity.strOperativeID + "-" + // operativeID 
                getNextNumber() + // counter 
                ".jpg" 

but i require, files name should look like below:

B-13-04-006.jpg

and

B-05-07-008.jpg

Sun
  • 6,258
  • 22
  • 69
  • 124

4 Answers4

14

Use String.format("%02d", yournumber); to show 0 with a number if less than 10 (for two digits number).

Use method like

private String getPaddedNumber(int number) {
    return String.format("%02d", number);
}

You can read Formatter documents for more details.


How to use into your code

"B-" + // prefix
        getPaddedNumber(LoginActivity.strEventID) + "-" + // eventID 
        getPaddedNumber(LoginActivity.strOperativeID) + "-" + // operativeID 
        getPaddedNumber(getNextNumber()) + // counter 
        ".jpg"
Pankaj Kumar
  • 78,055
  • 25
  • 161
  • 180
3

As you seem to have strings that need to be (optionally) padded with zeros, you can use a different approach than generally used to pad integers:

public String addPadding(int length, String text) {
    StringBuilder sb = new StringBuilder();

    // First, add (length - 'length of text') number of '0'
    for (int i = length - text.length(); i > 0; i--) {
        sb.append('0');
    }

    // Next, add string itself
    sb.append(text);
    return sb.toString();
}

so you can use:

"B-" + // prefix
    addPadding(2, LoginActivity.strEventID) + "-" + // eventID 
    addPadding(2, LoginActivity.strOperativeID) + "-" + // operativeID 
    getNextNumber() + // counter 
    ".jpg"

There are lots of other possibilities to pad a String, see this question for more details/possibilities.

Community
  • 1
  • 1
Veger
  • 34,172
  • 10
  • 101
  • 111
1
public static String convert(int n){
    return n < 10 ? "0" + n : "" + n;
}
peter.petrov
  • 34,474
  • 11
  • 63
  • 118
0

http://openbook.galileocomputing.de/javainsel/javainsel_04_011.html#dodtp6223d54a-d5d8-4ea7-a487-03f519d21c6b

Just use a formatter. I think this is the easiest and most accurate approach

PKlumpp
  • 3,965
  • 6
  • 31
  • 55