Swiss
Swiss

Reputation: 1300

Cast float to int in OCaml

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.

Upvotes: 16

Views: 23495

Answers (2)

tolitius
tolitius

Reputation: 22549

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

Upvotes: 9

Pascal Cuoq
Pascal Cuoq

Reputation: 80325

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

Upvotes: 25

Related Questions