AppleScript - how to count integer length? So I was making this program that would write every number between 0 and 9999, but I need it to be 4 characters long no matter what the digit count is - the only way to do that, I think, is to have the program count the digits and then put it into a variable, subtracting that variable from 4 and adding that number of zeros before the number itself.

How can AppleScript count the digits? Is there even a way to do it at all?
Apple Developer > Mac Automation Scripting Guide contains an example how to add leading zeros to a number as AppleScript as well as JavaScript code:


  Adding Leading Zeros to a Number
  
  The handlers in Listing 20-11 and Listing 20-12 convert a number to a string and prepends it with leading zeros until it reaches a certain length. They accept two parameters—the number to add leading zeros to and the maximum number of leading zeros to add. For example, if the maximum number of leading zeros is set to 2, the results range from 001 to 999. If the maximum number of leading zeros is 3, the results range from 0001 to 9999, and so on.


AppleScript listing:

on addLeadingZerosToNumber(theNumber, theMaxLeadingZeroCount)
    -- Determine if the number is negative
    set isNegative to theNumber is less than 0

    -- Determine when the maximum number of digits will be reached
    set theThreshold to (10 ^ theMaxLeadingZeroCount) as integer

    -- If the number is shorter than the maximum number of digits
    if theNumber is less than theThreshold then
        -- If the number is negative, convert it to positive
        if isNegative = true then set theNumber to -theNumber

        -- Add the zeros to the number
        set theLeadingZeros to ""
        set theDigitCount to length of ((theNumber div 1) as string)
        set theCharacterCount to (theMaxLeadingZeroCount + 1) - theDigitCount
        repeat theCharacterCount times
            set theLeadingZeros to (theLeadingZeros &amp; "0") as string
        end repeat

        -- Make the number negative, if it was previously negative
        if isNegative = true then set theLeadingZeros to "-" &amp; theLeadingZeros

        -- Return the prefixed number
        return (theLeadingZeros &amp; (theNumber as text)) as string

      -- If the number is greater than or equal to the maximum number of digits
    else
        -- Return the original number
        return theNumber as text
    end if
end addLeadingZerosToNumber


If you prefer JavaScript check the link.