Decimal floating point arithmetic

Is there a decimal data type in OCaml which doesn’t have the classic binary representation problem?

# 1.1 +. 2.2;;
- : float = 3.3000000000000003

Thank you!

You can use Zarith [1]. Note that it works with rational numbers, not
"decimal" stricto sensu, but it might suit your needs.

[1] https://github.com/ocaml/Zarith

4 Likes

This said, some people doing finance calculations need decimal rather than binary representations. Gnu MP won’t do it, but GNU MPFR will.

That’s my use case indeed. I have to work with a lot of small monetary amounts and I can’t afford rounding (or representation) errors. The database provides and accepts numeric/decimal values.
Which data type do seasoned OCamlers use for calculations with monetary amounts?
Thank you all!

+1 for latin declination :slight_smile:

I think mostly people have been using arbitrary precision types and haven’t worried much about decimal vs. binary representation issues. You probably can get away with having arbitrary precision integers of the smallest unit of account (say, cents) that’s relevant, but yes, doing a variation of the arbitrary precision package that did decimal might be a good thing for the small subset of users that really need it.

Multiply all your values by 10 (or whatever the smallest coin value requires), and work with integers.

Won’t work if you need correct rounding.

Just fyi Kind of "financial" integer printing format - #8 by yawaramin

2 Likes

Thank you, I’ve been using “decimal” for a long time now. I should have marked this as an “answered question”, sorry, my bad. I’m still not used to these fancy new webforums. :slight_smile:

2 Likes

No problem, I just wanted to put it out there in case someone came across this thread later and got the impression OCaml doesn’t have a decimal type.

1 Like

@perry previously mentioned MPFR, so FYI it happens there exists some OCaml binding for MPFR: