Version 2 of Tcl based Packed Decimal Arithmetic

Updated 2002-02-25 19:52:24

During February 2002, Gerald Lester posted version 0.1 of the following code, designed to be a script level package for performing precise math against decimal numbers.

For more precision from a C based extension, check out mpexpr.

A similar Tcl-based implementation is at Arbitrary precision math procedures.


   package provide packedDecimal 0.1

   namespace eval packedDecimal {
       namespace export add subtract multiply divide setDecimals

       variable decimals 2
       variable formatString {%d.%2.2d}
       variable carry 100
   }

   proc packedDecimal::add {a b} {
       variable decimals
       variable formatString

       scan $a %d.%d a1 a2
       scan $b %d.%d b1 b2
       incr a2 $b2
       if {[string length $a2] > $decimals} then {
           incr a1 1
           set a2 [string range $a2 1 end]
       }
       incr a1 $b1
       return [format $formatString $a1 $a2]
   }

   proc packedDecimal::subtract {a b} {
       variable decimals
       variable formatString
       variable carry

       scan $a %d.%d a1 a2
       scan $b %d.%d b1 b2
       incr a2 -$b2
       if {$a2 < 0} then {
           incr b1 1
           set a2 [expr {$carry + $a2}]
       }
       incr a1 -$b1
       return [format $formatString $a1 $a2]
   }

   proc packedDecimal::multiple {a b} {
       variable decimals
       variable formatString

       return -code error {Sorry, Multiple is not yet implemented!}
   }

   proc packedDecimal::divide {a b} {
       variable decimals
       variable formatString

       return -code error {Sorry, Divide is not yet implemented!}
   }

   proc packedDecimal::setDecimals {a} {
       variable decimals
       variable formatString
       variable carry 100

       set formatString [format {%%d.%%%d.%dd} $a $a]
       set decimals $a
       set carry [format "1%${a}.${a}d" 0]
       return;
   }

   proc packedDecimal::getDecimals {} {
       variable decimals

       return $decimals
   }

Category Package, Category Mathematics