From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: weis Received: (from weis@localhost) by pauillac.inria.fr (8.7.6/8.7.3) id IAA31138 for caml-redistribution@pauillac.inria.fr; Tue, 26 Oct 1999 08:42:31 +0200 (MET DST) Resent-Message-Id: <199910260642.IAA31138@pauillac.inria.fr> Received: from nez-perce.inria.fr (nez-perce.inria.fr [192.93.2.78]) by pauillac.inria.fr (8.7.6/8.7.3) with ESMTP id BAA05383 for ; Tue, 26 Oct 1999 01:07:37 +0200 (MET DST) Received: from enst.enst.fr (enst.enst.fr [137.194.2.16]) by nez-perce.inria.fr (8.8.7/8.8.7) with ESMTP id BAA24081 for ; Tue, 26 Oct 1999 01:07:35 +0200 (MET DST) Received: from Montchapet.ecole (root@cal-ppp17.ppp.enst.fr [137.194.3.17]) by enst.enst.fr (8.9.1a/8.9.1) with ESMTP id BAA13782 for ; Tue, 26 Oct 1999 01:07:34 +0200 (MET DST) Received: from localhost (localhost [[UNIX: localhost]]) by Montchapet.ecole (8.9.3/8.9.3) id BAA03543 for caml-list; Tue, 26 Oct 1999 01:06:44 GMT From: Michel Quercia Reply-To: quercia@cal.enst.fr To: caml-list@Montchapet.ecole Subject: Re: How to format a float? Date: Tue, 26 Oct 1999 00:53:47 +0000 X-Mailer: KMail [version 1.0.17] Content-Type: text/plain References: <3813AA4E.7016C100@maxtal.com.au> MIME-Version: 1.0 Message-Id: <99102601064300.03249@Montchapet> Content-Transfer-Encoding: 8bit Content-Transfer-Encoding: 8bit Resent-From: weis@pauillac.inria.fr Resent-Date: Tue, 26 Oct 1999 08:42:31 +0200 Resent-To: caml-redistribution@pauillac.inria.fr Le lun, 25 oct 1999, vous avez écrit : : How do I format a floating point number : correctly in ocaml, with a given _variable_ : width and precision? Like this : let str width prec = let prec = min 8 (max prec 0) in let pow_ten = 10.0 ** float(prec) in fun x -> let y = abs_float(x) in let sgn= if x < 0. then -1. else 1. in let a = floor(y) in let b = 1. +. y -. a in let z = truncate(b*.pow_ten +. 0.5) in let sa = string_of_float(sgn*.a) in let sb = string_of_int(z) in let pad= width - String.length(sa) - prec - 1 in (String.make (max 0 pad) ' ') ^ sa ^ "." ^ (String.sub sb 1 prec) The "8" in "min 8 (max prec 0)" is here to avoid integer overflow when computing "z" on 32-bit computers. "b" is 1 too large in order to force "string_of_int(z)" having "prec+1" characters. Not very nice ... Perhaps an addition to the standard printf library routines in order to accept the "*" variable field length would be better. -- Michel Quercia 9/11 rue du grand rabbin Haguenauer, 54000 Nancy http://pauillac.inria.fr/~quercia mailto:quercia@cal.enst.fr