6

So I have a bit of code that is supposed to pad strings of with zeros if they have a length of less than six in order to get them up to six. To accomplish this I've used the String.leftPad(Integer, String) method.

String key = '1234';
key = key.leftPad(6 - key.length(), '0');

This is supposed to output the string 001234 however it's no longer working. This is code that has been in production for nearly six months. Looking at the documentation this method is not shown, though it compiles just fine and I would swear that it worked when I initially developed it.

Is this a bug? Was functionality removed? Did I somehow tap into something that I shouldn't have?

2
  • Don't think I can answer the question, but some years-old code of mine just used code like key = key.leftPad(6-key.length()).replace(' ', '0'); Can't imagine having done that if there was a leftpad(Integer, String) in the docs. – Derek F May 11 '16 at 18:08
  • @DerekF I can't really explain it. I don't know how I would've developed it had I not seen documentation on it somewhere. I mean, it does compile, what does that say? – dBeltowski May 11 '16 at 18:37
7

Looks like an undocumented feature to me.

Worked up a quick test in one of my dev environments, and I got it to both compile and work.

Strangely enough, it even works when I turn down the Salesforce API Version below the point where the leftPad() method was introduced (v26.0, page 181 of the release notes)

From my brief testing, this undocumented method behaves the same as with the documented leftPad(Integer) method. The integer passed should be the length of the output string. If the passed integer is less than/equal to the input string, then nothing is done (simply returns the input string).

This has been the documented behavior (ie. the passed integer being the target size of the resulting string instead of the number of characters to pad) for as long back in the docs as I can see (back to API v 29.0)

In your example, you end up calling key.leftPad(2, '0'), and as your key's length is 4, nothing happens.

If you change your call to key.leftPad(6, '0'), it should work as intended.

1
  • When I downgraded the API version below the documented version it worked for me too, but once I packaged my code it stopped working and gave unexpected results. – Randall Flagg Jun 17 '19 at 8:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.