OCaml's standard library includes several floating-point functions equivalent to C ones, such as mod_float for C's fmod(), the exponentiation operator ** for C's pow(), and other functions such as ceil, log, etc.
But does it also include equivalents for round() and trunc()? There is truncate/int_of_float, but their type is float -> int and not float -> float.
It contains the
modffunction, that is a swiss-knife function, with which you can define thetruncatefandroundffunctions:The
roundfunction also can be expressed withmodfHowever it can be expressed more succinctly (and efficiently) with
floorBut both rounding functions are a little bit buggy, as comment in
core's implementation states:So a little bit more correct way to implement the rounding would be (from Core library):
But even this
round_nearestis not flawless, for example:This
0.49999999999999994is an immediate predecessor of0.5. Pascal's blog contains suggestions on how to solve this issue. The following should work in OCaml:And this is only one rounding policy, round to nearest (the intuitive one). There are other policies, that have their own caveats.