[Prev][Next][Index][Thread]

Re: Currency and Dylan



In article <wkaec8fcgt.fsf@double.co.nz>, Chris Double 
<chris@double.co.nz> wrote:

> What approaches do people use for dealing with dollar values in Dylan?
> In particular, making the dollar/cents add up
> correctly. <double-float>? <integer>? A special currency class?
> Reading/writing the dollar valuse to/from files as well. How do I do
> this with floats for example? 

How big amounts are you potentially dealing with?  Do you ever have to 
deal with fractions of a cent?

Whatever your basic unit is (cents, mils, ...), store your money as a 
double precision floating point number representing an exact integer 
multiple of the unit.  i.e. if you're working in cents, store $123.45 as 
12345.  IEEE FP operations on integer values are always exact (except 
division, of course) and you get a huge range: 9x10^13 dollars.

You could just use the naked floats, but you're probably better off 
using a class that automatically does...

  let v = val * 100;
  let (int, frac) = round(val); 
  value := v - frac;

... on input to convert from a floating point representation, and 
multiplies by 0.01 on output.

Fortunately, people never multiply $ by $, so you never need to rescale 
the results of arithmetic.

-- Bruce



References: