Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert integer to String Spring Controller

public ModelAndView showUserAppsByID(@PathVariable(name = "id") int id) {
   String emIDConvert= Integer.toString(id);

   // ...
}

This Controller format works but is not the same as what I expected.

Example:

  • id=3
  • id=43

My expectation:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • id=0003
  • id=0043

That main I want to format Integer to String varchar(4).

>Solution :

Java has nothing like varchar, just a String of a variable length or a character array with a fixed length (char[4]). Practically, everybody uses String, unless the character array is specifically required (for example passwords).

You can use a simple static method String#format to introduce the leading zeroes.

 String emIDConvert = String.format("%04d", id));

Demo:

String.format("%04d", 3));      // returns 0003
String.format("%04d", 34));     // returns 0034
String.format("%04d", 345));    // returns 0345
String.format("%04d", 3456));   // returns 3456
String.format("%04d", 34567));  // returns 34567

This method uses the java.util.Formatter, and the JavaDoc links to its details here.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading