在OCaml中将float强制转换为int

在OCaml中将float强制转换为int,ocaml,Ocaml,在OCaml中如何将浮点转换为整数 我知道如何从浮点值中获取浮点值,但从浮点值中获取浮点值似乎不是一个简单的方法;; # int_of_float ;; - : float -> int = <fun> -:float->int= 我假设您想要一个附近的int(这一轮接近于零,与C一样) 如果您想要IEEE表示,请参见Int64。浮点的位

在OCaml中如何将浮点转换为整数

我知道如何从浮点值中获取浮点值,但从浮点值中获取浮点值似乎不是一个简单的方法;;
# int_of_float ;;
- : float -> int = <fun>
-:float->int= 我假设您想要一个附近的
int
(这一轮接近于零,与C一样)


如果您想要IEEE表示,请参见
Int64。浮点的位

如果浮点的整数部分是您想要的,您可以简单地
截断它:

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
 *)
或者
floor
/
ceil
,然后
截断
,如果您确实想将其四舍五入到最接近的整数