Skip to main content
nikos101
Inspiring
August 17, 2009
Answered

cfscript I'm trying to write Please help :)

  • August 17, 2009
  • 2 replies
  • 1001 views

I wonder if some one could help with a cfscript I'm trying to write.

A have a number eg

135

4245

1

I want to turn these into a string with length 6 with zeros at the start like so:

000135

004245

000001

thx 4 any ideas

    This topic has been closed for replies.
    Correct answer Prasanth_Kumar_S

    Use numberformat()

    tmpNo = 523;

    numberformat(tmpNo,"000000");

    2 replies

    Prasanth_Kumar_S
    Prasanth_Kumar_SCorrect answer
    Inspiring
    August 17, 2009

    Use numberformat()

    tmpNo = 523;

    numberformat(tmpNo,"000000");

    nikos101
    nikos101Author
    Inspiring
    August 18, 2009

    thanks friends

    Inspiring
    August 18, 2009

    Here's a cfscript along the lines of what you asked for. There's other ways to do it, of course, but I thought this approach would be helpful to you.

    <cfscript>
    /* takes a string as an argument and adds as many zeroes as it takes to make the string be exactly 6 characters. */
    function PadWithZeroes()
    {
    var VarToTest = "";
    var ValToReturn = "";
    var VarLen = 0;
    var DesiredVarLen = 6;

    if (StructCount(Arguments) EQ 1)
        {
        /* Use Trim(Arguments[1]) only if you do NOT want to add zeroes to one or more empty spaces */
        VarToTest = Trim(Arguments[1]);
        VarLen = Len(VarToTest);
        TimesToLoop = DesiredVarLen - VarLen;
        }

    if (TimesToLoop GT 0)
        {
        for (q = 1; q LTE TimesToLoop; q = q + 1)
            {
            VarToTest = "0" & VarToTest;
            }
        ValToReturn = VarToTest;
        return ValToReturn;
        }
    else
        {
        return false;
        }
    }

    // the rest is for testing/viewing the function etc.

    NumberToUse = 4;
    if (IsDefined("URL.NumberToUse") AND Len(Trim(URL.NumberToUse)) LTE 6)
        {
        NumberToUse = Trim(URL.NumberToUse);
        }

    </cfscript>


    <cfoutput>

    <br>

    NumberToUse=#NumberToUse#

    <br>
    <br>
    PadWithZeroes(NumberToUse) = #PadWithZeroes(NumberToUse)#
    <br>
    <br>

    </cfoutput>

    Inspiring
    August 17, 2009

    It is a good idea to check google first. This is a very common question

    http://tinyurl.com/o9nvue