Skip to main content
December 8, 2008
Question

How to insert specific characters into a string based on string length?

  • December 8, 2008
  • 3 replies
  • 358 views
I have a field called street number on a form where the user enters a street number. The user may enter up to 5 digits. It is stored in the database as a 5 character field. If the street number is 556, it is stored in the table as '00556'. If it is '1234', it is stored in the table as '01234'. As you can see, if its less than 5 characters, the field name must have leading zero's.

I'm trying to write a function that converts the number that was input by the user. How do I do this? I tried a similar approach to Python where its as simple as 5 * '0' would give you '00000' or 5 * 'a' would give you 'aaaaa'.

Here's what I tried:
<cfif len(streetnum) LT 5>
<cfset new_streetnum = (5 - len(streetnum) * '0') & streetnum>
</cfif>

But this doesn't work in ColdFusion. I'm sure there's an easy way to do this.
    This topic has been closed for replies.

    3 replies

    Inspiring
    December 9, 2008
    or you can use CF's repeatstring() function:

    <cfset streetnum = repeatstring('0', 5 - len(trim(streetnum))) &
    trim(streetnum)>

    you don;t even need to wrap it in <cfif> - if the length of streetnum is
    5 then nothing will be added by repeatstring() function.

    Azadi Saryev
    Sabai-dee.com
    http://www.sabai-dee.com/
    Inspiring
    December 8, 2008
    Or, prepend the number of zeros you want and do a right() on the result.
    Inspiring
    December 8, 2008
    <cfset new_streetnum = replace(lJustify(streetnum,5),' ','0')>

    The lJustify() and rJustify() functions let you create a space padded
    string of a given length.

    Then you can just replace the spaces with zeros.