Version française
Home     About     Download     Resources     Contact us    
Browse thread
Re: localization, internationalization and Caml
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Michel Quercia <quercia@c...>
Subject: Re: How to format a float?
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