16

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.

Swiss
  • 1,260
  • 2
  • 17
  • 29

2 Answers2

25
# 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.

Pascal Cuoq
  • 79,187
  • 7
  • 161
  • 281
9

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

tolitius
  • 22,149
  • 6
  • 70
  • 81