"IllegalFormatConversionException: d != java.lang.String" when padding number with 0s?
Solution 1
You don't need the Integer.toString()
:
newPK = String.format("%08d", lastRecord);
String.format()
will do the conversion and the padding.
Solution 2
Very late to the party.
If you still are facing an issue to the String.format();
code even after implementing accepted answer.
This did not work for me:
String.format("%08d", stringvariable);
Because of two reasons:
- It will not work as
d
will expect for decimal point not string. - Use
%8d
instead of%08d
as formatter did not work for me if I used this%08d
If you are using String based Variable with String data. Use this.
String.format("%8s", stringvariable);
Solution 3
It worked for me, It should be integer here 12 should be integer.
String.format("%04d", Integer.parseInt("12"));
output - 0012
Metal Wing
Updated on August 24, 2021Comments
-
Metal Wing almost 3 years
I had a perfectly working code yesterday, in the exact form of:
int lastRecord = 1; String key = String.format("%08d", Integer.toString(lastRecord));
Which would pad it nicely to 00000001.
Now I kicked it up a notch with twoKeyChar getting a string from a table and lastRecord getting an int from a table.
As you can see the concept is essentially the same - I convert an int to a string and try to pad it with 0s; however, this time I get the following error:
java.util.IllegalFormatConversionException: d != java.lang.String
The code is below:
String newPK = null; String twoCharKey = getTwoCharKey(tablename); if (twoCharKey != null) { int lastRecord = getLastRecord(tablename); lastRecord++; //The println below outputs the correct values: "RU" and 11. System.out.println("twocharkey:"+twoCharKey+"record:"+lastRecord+"<"); //Now just to make it RU00000011 newPK = String.format("%08d", Integer.toString(lastRecord)); newPK = twoCharKey.concat(newPK); }
I feel like I must have typed something wrong, because there is no reason for it to break since the last time when it worked. Any help/hint is appreciated! Thank You!
-
Metal Wing about 12 yearsI am going to go to my corner, feeling dumb... Nice catch! Thank You! Will accept answer in 10min when it lets me, heh.
-
Somaiah Kumbera almost 11 yearsIts not that you don't NEED to do the toString, but more like you CANNOT. The "d" in the first argument to String format expects a decimal integer. Hence the error.
-
Morten Holmgaard about 2 yearsI test this exact error with %1$d parsing int zero to it..
-
CoolMind about 2 years@MortenHolmgaard, sorry, what should I a answer? :)