Leading zeros

How to convert numbers to numeric strings padded with leading zeros. This also extols the virtues of treating numbers as numbers wherever possible.

OS version: Any

(* The popular method for producing numeric strings padded to a certain length
   with leading zeros involves the implicit coercion of a number to string, the
   concatenation of this string to another consisting of enough "0" characters,
   and the extraction of the required substring from the end of the result.
   Thus, with an integer value between 0 and 99 and a required string length of
   two characters: *)

text -2 thru -1 of ("0" & n)

(* Maths operations generally make less work for the processor than manipulating
   text, so it would be more efficient to replace the string concatenation with
   a simple addition. The coercion would then have to be explicit: *)

text -2 thru -1 of ((100 + n) as string)

(* This executes much more quickly and, since the coerced string is now always
   the same length, it's possible to use positive indices in the extraction of
   the substring, which is slightly faster still: *)

text 2 thru 3 of ((100 + n) as string)

(* When creating two or more such strings - perhaps for combining into a short-
   date string - it's possible for all the coercions to be combined into one.
   Just calculate a number containing all the digits and coerce that. The caveat
   here is that the number to be coerced shouldn't become so huge that it's
   rendered in scientific notation. With short dates, though, it won't. *)

set yyyymmdd to (yearNum * 10000 + monthNum * 100 + dayNum) as string
set yy to text 3 thru 4 of yyyymmdd -- 'text 1 thru 4' to include the "century"
set mm to text 5 thru 6 of yyyymmdd
set dd to text 7 thru 8 of yyyymmdd

(* Or, for less typing: *)

tell (yearNum * 10000 + monthNum * 100 + dayNum) as string
  set yy to text 3 thru 4
  set mm to text 5 thru 6
  set dd to text 7 thru 8
end tell

-- NG