Re: How to format a float?

From: Michel Quercia (quercia@cal.enst.fr)
Date: Tue Oct 26 1999 - 02:53:47 MET DST


From: Michel Quercia <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
Message-Id: <99102601064300.03249@Montchapet>

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



This archive was generated by hypermail 2b29 : Sun Jan 02 2000 - 11:58:27 MET