English version
Accueil     À propos     Téléchargement     Ressources     Contactez-nous    

Ce site est rarement mis à jour. Pour les informations les plus récentes, rendez-vous sur le nouveau site OCaml à l'adresse ocaml.org.

Browse thread
Strange behaviour of string_of_float
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2008-06-23 (08:50)
From: Olivier Andrieu <oandrieu@g...>
Subject: Re: [Caml-list] Strange behaviour of string_of_float
On Mon, Jun 23, 2008 at 10:32, Mattias Engdegård <mattias@virtutech.se> wrote:
>>My intent is to extract an ASCII representation of an OCaml float
>>value so that it can be used to recreate *exactly* the same value, at
>>least on the same architecture.
> A somewhat more portable (and readable, maybe) representation of
> floating-point numbers is in hex (a la C99). It is independent of the
> precision and binary format used. Unfortunately, ocaml's Printf has
> already appropriated %a for a different purpose, but it remains a good
> option for those willing to do some manual work.
> I have used it in the past to good effect in text-based interchange
> formats between applications written in C.

Indeed, that's a good solution. It's possible to use this %a
conversion directly, without  writing external C code:

  (* this external is in pervasives.ml *)
  external format_float : string -> float -> string = "caml_format_float"
  let hex_string_of_float f =
    format_float "%a" f

# hex_string_of_float pi ;;
- : string = "0x1.921fb54442d18p+1"

Mind that this only works if the underlying C library knows how to
handle this C99 conversion specifier (MSVC6 doesn't for instance).