How To – Pad Zeros (prefix or suffix)

Background Knowledge


There is certain times when one needs to pad zeros to the beginning (prefix) or ending (suffix) of a integer.

Below is what I came up with for a solution in JavaScript. All one has to do is call the function with the integer value, the length (integer) of the padding and position to place the padding. Use “start” for the prefix or use “end” for the suffix. Please lets see some comments on how to improve this small block of code.

Solution


1
2
3
4
5
6
7
8
9
10
11
function fnPaddingZeros(nInterger,nPaddingLength,szPaddingPos)
{
	//convert integer to string
	nInterger=nInterger.toString();
	while(nInterger.length < nPaddingLength)
	{
		if(szPaddingPos == "start") { nInterger = '0' + nInterger; }
		else if(szPaddingPos == "end") { nInterger = nInterger + '0'; }
	}
	return nInterger;
}