Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast float to int in OCaml

Tags:

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.

like image 965
Swiss Avatar asked Oct 23 '11 19:10

Swiss


2 Answers

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

like image 130
Pascal Cuoq Avatar answered Sep 17 '22 12:09

Pascal Cuoq


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

like image 41
tolitius Avatar answered Sep 17 '22 12:09

tolitius