Rounding floats to number of decimals?

Float.round: float -> float rounds a float to the nearest integer. I’m looking for a rounding function that lets me round to a given number of decimals. My first idea would be something like:

let round2 n = Float.(n *. 100.0 |> round |> fun x -> x /. 100.0);;

# round2 Float.pi;;
- : float = 3.14

Any better idea?

1 Like

You can have a look at Gg's Float.round_dfrac function. The code is here.


By the way, I know this pipe operator became fashionable. However not only does it make the code less obvious than it could be, but in general if you write your divisions that way it increases the chances you won’t benefit from OCaml’s float unboxing (you won’t if the function doesn’t get inlined).

I don’t really see what is wrong with writing:

let round2 n = Float.round (n *. 100.) /. 100.