Cast float to int in OCaml

孤街醉人 提交于 2019-12-06 19:03:14

问题


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.


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/7868424/cast-float-to-int-in-ocaml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!