TExcelTAD
Home › OCaml › OCaml Type Conversion

OCaml Type Conversion

OCaml never converts a value from one type to another behind your back. When you need an int as a float, or a number as a string, you call a conversion function. The names follow the pattern target_of_source, and each module also offers Module.of_x / Module.to_x versions.

Numbers

ocaml · try it yourself
let () =
  let items = 7 in
  let total = 23.5 in
  let average = total /. float_of_int items in
  Printf.printf "average = %.3f\n" average;
  Printf.printf "%d\n" (int_of_float 3.99);
  Printf.printf "%d\n" (int_of_float (-3.99));
  Printf.printf "%.1f %.1f %.1f\n" (Float.round 2.5) (floor 2.7) (ceil 2.1);
  Printf.printf "%d\n" (Float.to_int (Float.round 2.5))
average = 3.357
3
-3
3.0 2.0 3.0
3

int_of_float truncates towards zero, so 3.99 becomes 3 and -3.99 becomes -3. Round first with Float.round (halves go away from zero), floor or ceil when you want a different rule. float is a shorter alias for float_of_int.

From → To Function
int → float float_of_int, float, Float.of_int
float → int int_of_float, Float.to_int (truncates)
int → string string_of_int, Int.to_string
float → string string_of_float, Float.to_string, Printf.sprintf "%.2f"
bool → string string_of_bool, Bool.to_string
char → int Char.code
int → char Char.chr
char → string String.make 1 c, String.make 1

Converting to strings

ocaml · try it yourself
let () =
  let score = 87 in
  let ratio = 0.875 in
  print_endline ("score: " ^ string_of_int score);
  print_endline ("ratio: " ^ string_of_float ratio);
  print_endline ("passed: " ^ string_of_bool (score >= 50));
  print_endline (Printf.sprintf "ratio: %.1f%%" (ratio *. 100.));
  print_endline (String.make 1 'A' ^ String.make 3 'h')
score: 87
ratio: 0.875
passed: true
ratio: 87.5%
Ahhh

Printf.sprintf works like printf but returns the string instead of printing it. It is the most flexible way to build formatted text. %% prints a literal percent sign.

Parsing strings

Turning a string into a number can fail, so there are two styles:

  • int_of_string s raises the exception Failure "int_of_string" on bad input.
  • int_of_string_opt s returns an option: Some n on success, None on failure.
ocaml · try it yourself
let show_parse s =
  match int_of_string_opt s with
  | Some n -> Printf.printf "%S -> %d\n" s n
  | None -> Printf.printf "%S is not an int\n" s

let () =
  show_parse "42";
  show_parse "-17";
  show_parse "0x1F";
  show_parse "4.5";
  show_parse "seven";
  Printf.printf "%.2f\n" (float_of_string "2.5e3");
  Printf.printf "%b\n" (bool_of_string "true")
"42" -> 42
"-17" -> -17
"0x1F" -> 31
"4.5" is not an int
"seven" is not an int
2500.00
true

%S prints a string with quotes and escapes, handy for showing exactly what the input was. Notice that int_of_string understands OCaml literal syntax, including 0x for hexadecimal.

Tip: Prefer the _opt functions for user input. They force you to handle the failure case with match, which you will learn about in the options lesson.

What happens without the _opt version

ocaml · try it yourself
let () =
  print_endline "parsing...";
  let n = int_of_string "12a" in
  Printf.printf "got %d\n" n
parsing...
Fatal error: exception Failure("int_of_string")

The uncaught exception stops the program. You will learn to catch exceptions with try ... with later.

Test yourself

What is int_of_float (-2.7)?

  1. -3
  2. -2
  3. 3
  4. A compile error

What does int_of_string_opt "abc" return?

  1. 0
  2. None
  3. It raises Failure
  4. Some 0

Which function builds a formatted string without printing it?

  1. Printf.printf
  2. print_string
  3. Printf.sprintf
  4. string_of_format