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?
CodePudding user response:
Try this:
String foo = String.format("d", bar);
That will add the correct amount of 0's to the beginning of the string.