Sunday, 18 November 2018

Java, return formatted string of an int




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


Answer



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);
}

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...