Version 1 of Floating-point formatting

Updated 2003-02-11 18:10:22

Arjen Markus (11 february 2003) I had a question from a customer about numbers that were displayed with too many digits, like "28.000" instead of "28.0". So, this raised the question: what can we do to make the appearance of (floating-point) numbers more elegant?

As it turns out, the format command has a lot of options, one of them is the # attribute to %g. Now, if all you have is the textual description of the effects, you will be very puzzled indeed.

So, here is a little script that examines the effects:

   # Check the effects of the various formats for floating-point numbers
   #
   foreach value {1.0 -1.0 1.01 -1.01 0.00001 -0.00001 1000000.0 -1000000.0} {
      set result ""
      foreach form {%g %-g %6g %6.4g %#.4g %06g %-6g} {
         append result [format " >$form<" $value]
      }
    puts "Value $value: $result"
   }

I have reformatted the output a bit, to get the following table:

  Formats:           %g       %-g       %6g       %6.4g     %#.4g        %06g   %-6g
  Value 1.0:         >1<      >1<       >     1<  >     1<  >1.000<      >000001< >1     <
  Value -1.0:        >-1<     >-1<      >    -1<  >    -1<  >-1.000<     >-00001< >-1     <
  Value 1.01:        >1.01<   >1.01<    >  1.01<  >  1.01<  >1.010<      >001.01< >1.01  <
  Value -1.01:       >-1.01<  >-1.01<   > -1.01<  > -1.01<  >-1.010<     >-01.01< >-1.01 <
  Value 0.00001:     >1e-05<  >1e-05<   > 1e-05<  > 1e-05<  >1.000e-05<  >01e-05< >1e-05 <
  Value -0.00001:    >-1e-05< >-1e-05<  >-1e-05<  >-1e-05<  >-1.000e-05< >-1e-05< >-1e-05<
  Value 1000000.0:   >1e+06<  >1e+06<   > 1e+06<  > 1e+06<  >1.000e+06<  >01e+06< >1e-06 <
  Value -1000000.0:  >-1e+06< >-1e+06<  >-1e+06<  >-1e+06<  >-1.000e+06< >-1e+06< >-1e+06<

[ Arts and crafts of Tcl-Tk programming ]