If you want to print the textual representation of a float in a file, perhaps the simplest:
output_string outf (string_of_float myfloat)
If you want to print a float on the console, you can use
print_string (string_of_float myfloat)
Of course, Printf.printf can also do this and more, so you should know it.
If you want to output a binary representation of a float , things will be more complicated. Since the float value is represented as an IEEE 754 double , it is 8 bytes, which can be written in different orders depending on the platform. In the case of a little-endian order, as usual in X86, you can use the following:
let output_float_le otch fv = let bits = ref (Int64.bits_of_float fv) in for i = 0 to 7 do let byte = Int64.to_int (Int64.logand !bits 0xffL) in bits := Int64.shift_right_logical !bits 8; output_byte otch byte done
The recorded float value can be read with the following:
let input_float_le inch = let bits = ref 0L in for i = 0 to 7 do let byte = input_byte inch in bits := Int64.logor !bits (Int64.shift_left (Int64.of_int byte) (8 * i)) done; Int64.float_of_bits !bits
This has the advantage that it is a very compact way to accurately store the float in a file, that is, what you write will be considered exactly as it was originally. For example, I did this at the interactive top level:
# let otch = open_out_bin "Desktop/foo.bin" ;; val otch : out_channel = <abstr> # output_float_le otch 0.5 ;; - : unit = () # output_float_le otch 1.5 ;; - : unit = () # output_float_le otch (1. /. 3.) ;; - : unit = () # close_out otch ;; - : unit = () # let inch = open_in_bin "Desktop/foo.bin" ;; val inch : in_channel = <abstr> # input_float_le inch ;; - : float = 0.5 # input_float_le inch ;; - : float = 1.5 # input_float_le inch ;; - : float = 0.333333333333333315 # close_in inch ;; - : unit = ()
and, as you can see, I returned what I put into the file. The disadvantage of this form of writing floats to files is that the result is not human-readable (indeed, the file is binary by definition), and you lose the ability to interact with other programs, such as Excel, which generally exchange data in a readable text form (CSV, XML, etc.).