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

How can I format a string to insert a leading zero if the input was a single-letter literal?

Is it possible to format string like 05 if input was 5 (one literal)?

 System.out.println(String.format("%d", 5)); //it should be 05
 System.out.println(String.format("%d", 15)); //15

>Solution :

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

Yes, you can achieve this by using the %02d format specifier in String.format(). The 0 indicates that you want to pad with zeros, and the 2 specifies the minimum width, ensuring that there are at least two characters. If the number has only one digit, it will be padded with a leading zero.

Here’s how you can use it:

System.out.println(String.format("%02d", 5));  // Outputs: 05
System.out.println(String.format("%02d", 15)); // Outputs: 15

In this example, %02d ensures that the output is at least two digits, padding with zeros if necessary.

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