I am trying to use format to display a set of real numbers in a
particular number of digits. I can control the size of the decimal part
to 2 digits. Is there a way I can specify a maximum length for the
integer part? In my case I would like to limit the length of the result
to 5 characters total. If a number doesn't fit into that length, then
perhaps return "*" instead of the number by going over the length limit.
This is OK:
% format "%5.2f" 12.345
12.35
These are not:
% format "%5.2f" 123.45
123.45
% format "%5.2f" 12345.67
12345.67
Tcl's [format] is very similar to C's sprintf() in that you can
specify a minimum width, but more is taken as needed. You want more
like a FORTRAN model, and in a few lines of code you can have that:
proc strictformat {fmt value} {
set f [format $fmt $value]
regexp {%(\d+)} $fmt -> maxwidth
if {[string length $f]>$maxwidth} {
return [string repeat * $maxwidth]
} else {return $f}
}
% strictformat %5.2f 12.345
12.35
% strictformat %5.2f 123.45
*****
% strictformat %5.2f 1234567
*****
Thanks for the solution; it will work. However, I was looking for a
solution within the format itself; like a switch that I could use within
regular format strings.
> However, I was looking for a
>solution within the format itself; like a switch that I could use within
>regular format strings.
But surely that's exactly the point of Tcl... if you don't like what's
there, make your own...
rename format _format
proc format {args} {
if {[string equal [lindex $args 0] -strict]} {
eval strictformat $args
} else {
eval _format $args
}
}
Or if you want to control this strictness item-by-item, you
would need to do a bit more work but it's still possible...
format strings are easy enough to parse.
--
Jonathan Bromley, Consultant
DOULOS - Developing Design Know-how
VHDL * Verilog * SystemC * e * Perl * Tcl/Tk * Project Services
Doulos Ltd., 22 Market Place, Ringwood, BH24 1AW, UK
jonathan...@MYCOMPANY.com
http://www.MYCOMPANY.com
The contents of this message may contain personal views which
are not the views of Doulos Ltd., unless specifically stated.
Ain't none. See the other reply to your post.
Why are you so concerned with only using "solution within the format itself"?
--
+--------------------------------+---------------------------------------+
| Gerald W. Lester |
|"The man who fights for his ideals is the man who is alive." - Cervantes|
+------------------------------------------------------------------------+
No reason, really; just laziness. I know it can be done in many ways
(thanks suchenwi and Jonathan) and even on an item by item basis. For
some reason I found it odd that the maximum lengths were not enforced.
Thanks for all replies!
According to the man page, there are no maximum lengths, there are
minimum widths. In %5.2f, the minimum width is 5. This includes the
decimal point. [format %5.2f 1.23] returns ' 1.23', with a space at
the front.