An AppleScript Function to Zero Pad a Value

by Ken Clark on October 22, 2009

I wrote this subroutine tonight as I watched Game 5 of the ALCS.  It takes a number and a desired length and then zero pads it.

on zero_pad(value, string_length)
	set string_zeroes to ""
	set digits_to_pad to string_length - (length of (value as string))
	if digits_to_pad > 0 then
		repeat digits_to_pad times
			set string_zeroes to string_zeroes & "0" as string
		end repeat
	end if
	set padded_value to string_zeroes & value as string
	return padded_value
end zero_pad

You could call it like this:

set new_value to zero_pad(7, 3)

…which would return a well-known secret agent’s alias:

007

Or you could call it like this:

set month to zero_pad(month of (current date),2)

…which for September would return a nicely zero-padded month value:

09

This worked exactly as I wanted it to, but if anyone out there has a more efficient way to do it I would love to see it.

  • Thomas
    Not so classy as yours, but short and functional:

    on zero_pad(value, string_length)
    set tmp_string to “000000000″ & (value as string)
    set padded_value to characters ((length of tmp_string) – string_length + 1) thru -1 of tmp_string as string
    return padded_value
    end zero_pad
  • Ken Clark
    Thomas--

    I never thought about approaching it like that (create a big padded string and then "chop it down" so to speak...), so it took a couple minutes for it to sink into my brain. I get it now. Very cool. Thanks for sharing. --Ken
blog comments powered by Disqus

Previous post:

Next post: