This made my day (float to string and string of float without loss of precision)

Useful trick when you want to save/load floats as text in a file without loss of precision:

(* float -> int64 -> string *)
(* convert float [x] to a string; no loss of precision *)
let exact_string_of_float (x: float): string =
  Int64.to_string (Int64.bits_of_float x)

(* string -> int64 -> float *)
(* decode float from string; no loss of precision *)
let exact_float_of_string (s: string): float =
  Int64.float_of_bits (Int64.of_string s)

I think @nojb told me this trick some time ago.

5 Likes

or

let exact_string_of_float (x : float) : string = Printf.sprintf "%h" x

let exact_float_of_string (s : string) : float = float_of_string s
6 Likes

Ok, even less code.
I guess it might be faster, also your solution has the advantage of hinting that the value is indeed a float and not an integer.