Version 5 of Narrow formatting

Updated 2005-07-19 23:36:53

if 0 {Richard Suchenwirth 2004-02-11 - Here's a routine for formatting non-negative integers (e.g. file sizes), so that the resulting field width does not exceed 5 characters, of which max. three significant digits, and K(ilo = 1024), M(ega = 1024^2) etc. modifiers are used for scaling. This may be useful on small displays.}


 proc fixform n {
    if {wide($n) < 1000} {return $n}
    foreach unit {K M G T P E} {
        set n [expr {$n/1024.}]
        if {$n < 1000} {
            set n [string range $n 0 3]
            regexp {(.+)\.$} $n -> n
            return $n$unit
        }
    }
    return Inf ;# :)
 }

if 0 { HJG Test: }

 proc Demo {n} { puts "$n = [fixform $n]" }

 catch {console show}
 Demo 1
 Demo 20
 Demo 300
 Demo 4000
 Demo 50000
 Demo 600000
 Demo 7000000
 Demo 80000000
 Demo 900000000

if 0 { Testing:

 % fixform 1
 1
 % fixform 10
 10
 % fixform 100
 100
 % fixform 1000
 0.97K
 % fixform 10000
 9.76K
 % fixform 100000
 97.6K
 % fixform 1000000
 976K
 % fixform 10000000
 9.53M
 % fixform 100000000
 95.3M
 % fixform 1000000000
 953M

}


In the Tcl chatroom I was informed that according to http://physics.nist.gov/cuu/Units/binary.html , the units based on powers of 2 should be abbreviated

 Ki Mi Gi Ti Pi Ei

but I haven't seen that used yet... change if you wish.

DKF: Some standards are just destined to be ignored...