Decimal 0.2.1 - arbitrary-precision decimal floating point

Happy to announce that decimal 0.2.1 has been pubished on opam.

decimal is a port of Python’s decimal module to OCaml and implements the General Decimal Arithmetic Specification. However note that it is a port in progress–basic arithmetic and rounding functions have been ported, but I am still working on powers and logs. The ported functions pass the same unit test suite that the Python version does (with some minor modifications).

Another caveat: currently the library is only supported on 64-bit architectures due to (exponent) overflow issues on 32-bit. If anyone is willing to test and fix overflows on 32-bit, I am more than happy to accept PRs.

Here’s an example of using the module:

(* Rosetta Code Currency Example *)

(* Demo purposes, normally you'd prefix module name or local open *)
open Decimal

let hamburger_qty = of_string "4_000_000_000_000_000"
let hamburger_amt = of_string "5.50"
let milkshake_qty = of_int 2
let milkshake_amt = of_string "2.86"

(* Shortcut to divide 7.65 by 100 *)
let tax_rate = of_string "7.65e-2"

let subtotal = hamburger_qty * hamburger_amt + milkshake_qty * milkshake_amt
let tax = round ~n:2 (subtotal * tax_rate)
let total = subtotal + tax

let () = Format.printf "Subtotal: %a
     Tax:  %a
   Total: %a\n" pp subtotal pp tax pp total

You can get the package with: opam install decimal. Minimum OCaml version 4.08.

8 Likes