Saturday, May 26, 2007

arbitrary precision decimal library

A week or so ago, I realized that I needed a decimal arithmetic library, so I decided to start working on one. That is to say, I didn't look around very hard to see if there were any existing CL-based libraries or FFI wrappers, since I was itching to work on something new.

Common Lisp already defines a rich set of number types and operations, including unbounded precision for integers and ratios. But there is no standard type providing exact decimal fraction representation and rounding. As an example, if we have a file containing company financial data, and we want to read that in, then do some computation on the data with amounts rounded correctly, we need to write some code.

So after a few evenings of work, I now have basic arithmetic operations implemented, including decimal division. I have a reader macro #D defined for convenience. And of course, I implemented several equivalents of the CL functions like incf, decf, zerop, signum, etc. I currently only support half-even (also known as banker's) rounding, since my primary intended use is for finance, and from what I understand half-even rounding theoretically does the best job of minimizing cumulative errors. I do know about IBM's spec, but my requirements aren't that sophisticated (yet).

I'm happy to share this code, if anyone's interested.