Converting Numbers to Dollars

Date:    Mon, 12 Jun 1995 18:19:23 EDT
From:    John Dowdell <71333.42@COMPUSERVE.COM>
Subject: Re: Converting Numbers to Dollars
Bill Roughen asks on June 11 how to format numbers to a currency format. This would involve turning the number into a string and manipulating it as such. Although possible implementations vary, the core approach remains the same -- hope that this entry from the Knowledge Base helps point out a workable direction for your particular application:
(Q) How can I multiply two user-entered numbers to get a dollar amount in a textfield?

(A) The following example will do this. It assumes that there are two editable textfields ("cost" and "units"), as well as a non-editable field named "total cost". It also assumes that we have set the "floatPrecision" property to a value of two, so that we display only two places after the decimal point.

    on mouseUp
      set temp = float(field "cost") * field "units"
      set temp = string(temp)
      set decimalPosition = offset(".", temp)
      if length(temp) - decimalPosition = 1 then put "0" after temp
      put "$" before temp
      put temp into field "total cost"
    end mouseUp
This is phrased as a button handler, although it could be used in many places. The first line does the multiplication. Note that the textfields are automatically converted to numbers for you, although we really should build in some error checking so the enduser does not enter their name. Only one "float" conversion is necessary, as the "units" field will automatically be promoted to a float.

We then find the position of the decimal point. A single-digit result will then be expanded to two digits after the decimal, if necessary. Finally, a dollar sign is prepended to the result and the whole entered into the display field.


PS: Please note that a report this spring points out a problem with using the Lingo "floatPrecision" property to cut off decimal numbers like that. On Windows, when increasing an order of magnitude you can have an improper jump (eg, set the "floatPrecision" to 2, and type "put 0.9999" into the Message Window). This only occurs on Windows and was discovered by the QA lab after release. Until this is addressed in a future version of Director, it would be better to use full-precision for calculations and then just truncate characters during the string manipulations, above.