Coyote's Guide to IDL Programming

Converting Numbers to Strings

QUESTION: I have a sequence of annimation frames that I want to display in IDL. On each frame, I want to overwrite the frame number on the image. How can I do this without hardcoding the numerical information in the program?

ANSWER: What you want to do is turn the frame number into a string and use IDL's ability to concatinate strings with the "+" sign. The easiest way to turn a number into a string is to use IDL's STRTRIM function, with the second positional parameter set to 2. This tells IDL to convert the number to a string, then trim blank characters from both ends of the resulting string. Thus, you get a nice, compact number.

The general form of the command looks like this:

   number = 15
   numberAsString = STRTRIM(number, 2)

Your annimation loop for the reqirement above might look something like this:

   FOR j=0, nframes-1 DO BEGIN
      TV, imageArray(*,*,j)
      XYOUTS, 0.1, 0.1, 'Frame ' + STRTRIM(j, 2), /NORMAL

Sometimes you wish the numbers to all have the same length. For example, suppose you wanted to name TIFF files so you can stitch them together into an AVI movie. You would like to have 50 files, named movie_01.tif to movie_50.tif. This can be done with the STRING function and the FORMAT keyword, like this:

   IDL> FOR j=0,49 DO Print, 'movie_' + STRING(j, FORMAT='(I2.2)'), + '.tif'

This method can also be used to turn floating point numbers into strings with a specified number of decimal places in the string:

   IDL> num = 3.1456784374
   IDL> Print, STRING(num, FORMAT='(F5.2)')

Note that converting a double precision number to a string is a bit more trouble than this. You may be interested in the cgNumber_Formatter program that can do all kinds of number conversions accurately.

You also have to be careful converting byte values to strings.

   IDL> Print, StrTrim(89B, 2)

The problem arises because there is a direct correlation between ASCII string values and bytes. If you have to convert a byte value to a string, be sure to cast the byte value to an integer first, like this.

   IDL> Print, StrTrim(Fix(89B), 2)

Natural Number Formatting

Sometime after IDL 6.0, the ability to specify the "natural" width of a number became possible with the FORMAT keyword to STRING. This has made a lot of things easier to do in IDL. The secret to obtaining natural width formatting is to use a zero as the "width" in the format string. Here is an example:

   IDL> number = 345.123456789D
   IDL> Print, String(number, Format='(D0.3)')

[Return to IDL Programming Tips]