How am I supposed to cast a float to an integer in OCaml?
I know how to get a float from an int, but there doesn't seem to be an easy way to get an int from a float.
# int_of_float ;;
- : float -> int = <fun>
I assume you want a nearby int
(this rounds towards zero, same as C does).
If you want the IEEE representation, see Int64.bits_of_float
.
you can simply truncate
it, if the integer part of the float is what you want:
printf "number\tint\tfloor\tceil\n";
List.iter
(fun x -> printf "%.1f\t%d\t%.1f\t%.1f\n" x (truncate x) (floor x) (ceil x))
fs;;
(*
* number int floor ceil
* 3.3 3 3.0 4.0
* 3.5 3 3.0 4.0
* 3.7 3 3.0 4.0
* -3.3 -3 -4.0 -3.0
*)
or floor
/ ceil
, and then truncate
, if you really want to round it up to the closest integer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With