Version franaise
Home About Download Resources Contact us
Browse thread
precision not working properly for strings in Printf?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Jonathan Bryant <jtbryant@v...>
Subject: Re: [Caml-list] precision not working properly for strings in Printf?

On Jun 26, 2007, at 11:18 PM, Quc Peyrot wrote:

> It seems that the precision field doesn't work properly with the  
> "s" type in Printf.printf:

It does work properly.  It's just not working the way you're  
expecting it to work.

>
> # Printf.printf "%.2s" "qwerty";;
> qwerty- : unit = ()
>
> This should print "qw"

No it shouldn't.  The width/precision specifier guarantees a  
_minimum_ length for strings, not an absolute length.  From the docs  
for Printf:

"The optional width is an integer indicating the minimal width of the  
result. For instance, %6d prints an integer, prefixing it with spaces  
to fill at least 6 characters.

The optional precision is a dot . followed by an integer indicating  
how many digits follow the decimal point in the %f, %e, and %E  
conversions. For instance, %.4f prints a float with 4 fractional  
digits."

Minimal length for width and precision doesn't apply to string  
conversions.  Here's how it works:

         Objective Caml version 3.09.3

# Printf.sprintf "%2s" "qwerty";;
- : string = "qwerty"

# Printf.sprintf "%.2s" "qwerty";;
- : string = "qwerty"

# Printf.sprintf "%5s" "a";;
- : string = "    a"

# Printf.sprintf "%.5s" "a";;
- : string = "    a"

Hope that helps.

--Jonathan

>
> -- 
> Best Regards,
> Quc
> _______________________________________________
> Caml-list mailing list. Subscription management:
> http://yquem.inria.fr/cgi-bin/mailman/listinfo/caml-list
> Archives: http://caml.inria.fr
> Beginner's list: http://groups.yahoo.com/group/ocaml_beginners
> Bug reports: http://caml.inria.fr/bin/caml-bugs