Question

I have just started studying Java and now I need to make an Java function that returns a formatted string representation of an int. This function must return "001" instead of just 1 and "010" instead of just 10, and so on... my function looks like this:

int value = 1;

public String getcountervalue() {
   String Return_string = Integer.toString(value);
   return (Return_string);
}

This is just a small part of an bigger code. the count of the value is handled by an other part of the code. I guess that the Integer.toString part will convert the int to an string, or?, but how can i make it properly formated (as explained above)?

I'm sorry if this question have been asked before, I where not able to find it.

I'm using java 1.7

Was it helpful?

Solution

There is a handy format() method, provided by String. See Oracle documentation

In your case, something like this should do it:

public String getCounterValue(int value) {
    return String.format("%03d", value);
}

OTHER TIPS

String.format("%02d", i);

or

for (i=0; i<=9; i++){
    System.out.println("00"+i)
}
for (i=10; i<=99; i++){
    System.out.println("0"+i)
}
if(i=100){
    System.out.println(i) 
}
public String getcountervalue() {
   String Return_string = Integer.toString(value);

   while(Return_string.length < 3){
       Return_string = '0'+Return_string;
   }

   return (Return_string);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top