Introduction
Last time I got a request from a client to limit a number to 6 digits and if the number has less than 6 digits, prepend 0 in front of it.Example: 7007 must become 007007
I had to do this in
- Javascript (for display in a disabled textbox) ,
- Visualforce (for display in a PDF), and
- Apex (to send to a Web Service).
Javascript
For the Javascript version, I wrote a small function that would do the left padding of zeroes. This function is called when the page is loaded.
function addZeroes(eId, size){
var elem = document.getElementById(eId)
while(elem.value.length < size)
elem.value = "0" + elem.value
}
The function takes the element Id and size as parameter to limit left padding. In my case the element was an input of type text:
<input id="agent_number" type="text" value="{!$User.Agent__c}" disabled="true"/>
The addZeroes() function was called as follows in a <script> tag after the form was loaded.
<script>
addZeroes("agent_number", 6);
</script>
Visualforce
The visualforce solution was hard to find but very simple to implement. I used the formula LPAD.
{!LPAD($User.Agent_No__c,6,'0')}
Apex
I could not find a solution that resembles the visualforce LPAD in Apex. I used two methods from the String Class to achieve the same result.
String agentNum = '7007';
String agentNumber = agentNum.leftPad(6).replace(' ', '0');
system.debug('## agentNumber : ' + agentNumber);
leftPad() method is used to pad spaces in front without exceeding the length parameter.
replace() method is used to replace all the spaces with 0.
Thnx & Cheers,
Gulshan.
replace() method is used to replace all the spaces with 0.
Thnx & Cheers,
Gulshan.