Binary Expressions

2008-10-7

How To - Pad Zeros (prefix or suffix)

Filed under: — Adam @ 1:00 pm

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;
}

Take back your mailbox - CAUCE.org

Powered By Wordpress PHP: Hypertext Preprocessor MySQL Powered Download Juice, the cross-platform podcast receiver
Proud To Be Canadian Get Firefox Valid XHTML Valid CSS
<NO>OOXML Logo


27 queries. 0.321 seconds.
Copyright © 2004 - 2005 by Adam Douglas