Version 4 of SYStems

Updated 2005-11-07 06:23:11

The Egyptian wannabe developer/sys-admin


 # Allow spaces and underscores in long number for easy reading
 proc norm {num} {
     if {[regexp {^(\s|\d|_)*(\.)?(\s|_)*(\d)+(\s|\d|_)*$} $num]} {
         string map {_ {} \  {}} $num
     } else {
         error "Number: $num is not in normal form"
     }
 }

 Example:
 expr [norm 10_000_000] + [norm 100._10_100]
 => 10000100.101

AMG: Neat! Here, this proc does the reverse (adds underscores):

 proc abnorm {num} {
     if {![string is double -strict $num]} {
         error "not a number: \"$num\""
     }
     set point [string first . $num]
     if {$point == -1} {
         set point [string length $num]
     } else {
         for {set pos [expr {$point + 4}]} {$pos < [string length $num]} {incr pos 4} {
             set num [string replace $num $pos $pos _[string index $num $pos]]
         }
     }
     for {set pos [expr {$point - 3}]} {$pos > 0} {incr pos -3} {
         set num [string replace $num $pos $pos _[string index $num $pos]]
     }
     return $num
 }

Example:

 % abnorm 100.10100
 100.101_00
 % abnorm 10000000
 10_000_000
 % abnorm 10000100.101
 10_000_100.101

This code doesn't handle exponential notation or even negative numbers. I don't want to put much more effort into it, since I'm more interested in seeing some clever [regsub] version. If anyone wants to give it a try, ... go right ahead. Have a blast.


Category Person