Skip to content Skip to sidebar Skip to footer

Show 0 As Prefix If Value Is Less Than 9

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

Solution 1:

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

Use method like

privateStringgetPaddedNumber(int number) {
    returnString.format("%02d", number);
}

You can read Formatter documents for more details.


How to use into your code

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

Solution 2:

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) {
    StringBuildersb=newStringBuilder();

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

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

so you can use:

"B-" + // prefixaddPadding(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.

Solution 3:

publicstaticStringconvert(int n){
    return n < 10 ? "0" + n : "" + n;
}

Solution 4:

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

Post a Comment for "Show 0 As Prefix If Value Is Less Than 9"