MacBook – AppleScript – how to count integer length

applescriptmacbook pro

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?

Best Answer

Here is a simple handler that, pads based on your question.

Example AppleScript code:

set theNumber to 1

set theNumber to padNumberAsString(theNumber)

on padNumberAsString(n)
    set theLength to (get length of (n as string))
    if theLength is equal to 1 then
        set n to "000" & n
    else if theLength is equal to 2 then
        set n to "00" & n
    else if theLength is equal to 3 then
        set n to "0" & n
    end if
    return n
end padNumberAsString

Result: "0001"


As a demo, this creates and displays a list of the padded numbers between 0 and 1000 to show the padding is taking place.

set thePaddedList to {}
repeat with i from 0 to 1000
    set end of thePaddedList to padNumberAsString(i)
end repeat
choose from list thePaddedList

on padNumberAsString(n)
    set theLength to (get length of (n as string))
    if theLength is equal to 1 then
        set n to "000" & n
    else if theLength is equal to 2 then
        set n to "00" & n
    else if theLength is equal to 3 then
        set n to "0" & n
    end if
    return n
end padNumberAsString