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!
You don't need the Integer.toString()
:
newPK = String.format("%08d", lastRecord);
String.format()
will do the conversion and the padding.
It worked for me, It should be integer here 12 should be integer.
String.format("%04d", Integer.parseInt("12"));
output - 0012
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:
d
will expect for decimal point not string.%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);
I our case with this problem it was do to java/kotlin conversion issue handling vargs because we had wrapped resources in a Kotlin file, where the missing trick was the flattern * operator
class LocalizedResources @Inject constructor(
@ApplicationContext context: Context
) {
private val resources = LokaliseResources(context)
fun getString(@StringRes resId: Int): String {
return resources.getString(resId)
}
fun getString(@StringRes resId: Int, vararg formatArgs: Any?): String {
return resources.getString(resId, *formatArgs)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With