This site is updated infrequently. For up-to-date information, please visit the new OCaml website at ocaml.org.

What library to use for arbitrary precision decimals
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
 Date: 2006-02-19 (15:44) From: Brian Hurt Subject: Re: [Caml-list] What library to use for arbitrary precision decimals
```

On Sun, 19 Feb 2006, Joshua Smith wrote:

> There are a couple of ways to handle money transactions without
> rounding errors.
>
> You could use the Nums library, which provides arbitrary precision
> calculations and numbers.   But even with arbitrary precision numbers,
> you still can have the situation where you get 405.0345 which if this
> were USD, you would still have to round if you wanted to pay someone
> this amount.  You will still have the arbitrary precision this way,
> however.
>
> The best way to handle money (in my experience) is to use integers.
> Then you can define conversion functions but only have to convert it
> to decimal for display purposes.  That way, even if you do a million
> transactions you won't lose any information.   You can also handle
> non-decimal based currencies/instruments/transactions that way[1]

I agree with this recommendation.  The basic idea is that you use fixed
point.  Say you want to be accurate to one thousandth of a cent (0.001
cents).  You simply do all calculations in terms of millicents.  So the
integer 1 represents one millicent.  One penny is represented as the
integer 1,000- one thousand millicents.  The amount \$2,345.67 is
represented by the integer 234,567,000.

If you use the Int64 module as the basis for your computations, you can
hold values up to \$184,467,440,737,095.51 in size.  This is larger than
the world's GDP, so it should be large enough.  32 bits isn't enough- that
only allows you to hold values up to \$42,949.67.

Brian

```