0

Like the title , I'm trying to add char Sequences to a String depending on my int values, EX : range from 1 -> 10000, bar = 22 so output must be 00022 What've tried and worked:

if (bar < 10)
 String foo = "0000" + String.valueOf(bar);
if (bar < 100 && bar >= 10)
 String foo = "000" + String.valueOf(bar);
if (bar < 1000 && bar >= 100)
 String foo = "00" + String.valueOf(bar);
if (bar >= 1000)
 String foo = "0" + String.valueOf(bar);

Is there any way to do this more simpler?

1 Answers1

0

Try this:

String foo = String.format("%05d", bar);

That will add the correct amount of 0's to the beginning of the string.

Dharman
  • 30,962
  • 25
  • 85
  • 135
SprintKeyz
  • 134
  • 8