Using RepeatString to create a mask in NumberFormat

{ Posted By : Eric Cobb on September 2, 2010 }
1166 Views
Related Categories: Tips 'n Tricks, CFML

Today I was working on creating a CSV file that required numeric columns to be a fixed number of digits, using leading zeros to make up the difference. So, for example, if the column required 5 digits, the number 123 should show up as 00123. This is super simple using the NumberFormat() function in CFML, simply specify a mask like so:

<cfset variables.myNum = NumberFormat(123,'00000')>
<cfoutput>#variables.myNum#</cfoutput>

But, in my particular case, I had several columns that required 12 and 15 digit numbers. Now, rather than go through bunch of NumberFormat() functions and count out 12 or 15 zeros, I came up with this little gem:

<cfset variables.myNum = NumberFormat(123,RepeatString(0,15))>
<cfoutput>#variables.myNum#</cfoutput>

I simply used the RepeatString() function to repeat "0" 15 times, and I used that to populate the mask of my NumberFormat() function. So, the above code renders the exact same thing as NumberFormat(123,'000000000000000'). The beauty of this is that, at a glace, you can tell how may zeros are in your NumberFormat mask, without having to constantly count them.

Comments
Carl Von Stetten's Gravatar If you have to do this a lot, with different lengths of padding, you might look at this UDF by Stephen Rittler:

http://cflib.org/udf/PadStringToLen

Carl
# Posted By Carl Von Stetten | 9/2/10 4:17 PM