[alt.sources] yet another formatter routine

nagel@ics.uci.edu (Mark Nagel) (02/27/90)

I just saw the number format routine posted in c.s.misc and thought
people might like to try mine.  I originally wrote this as an
extension to sc (spreadsheet calculator), and I sent the diffs to
the author of sc.  Seeing the post in c.s.misc made me think others
might want to see/use it.  It is based on the functional description
of the formatting done by Microsoft Excel, although it lacks some of
the more advanced features.  Good enough, as they say...  Please
send me any comments/fixes.

#! /bin/sh
# This is a shell archive.  Remove anything before this line, then unpack
# it by saving it into a file and typing "sh file".  To overwrite existing
# files, type "sh file -c".  You can also feed this as standard input via
# unshar, or by typing "sh <file", e.g..  If this archive is complete, you
# will see the following message at the end:
#		"End of shell archive."
# Contents:  Makefile format.c main.c xmalloc.c
# Wrapped by nagel@esp.ics.uci.edu on Mon Feb 26 20:19:14 1990
PATH=/bin:/usr/bin:/usr/ucb ; export PATH
if test -f 'Makefile' -a "${1}" != "-c" ; then
  echo shar: Will not clobber existing file \"'Makefile'\"
else
echo shar: Extracting \"'Makefile'\" \(1690 characters\)
sed "s/^X//" >'Makefile' <<'END_OF_FILE'
X#############################################################################
X#
X#  Makefile for fmt
X#
X#  $Id$
X#############################################################################
X#
X#  If you move this makefile, update the variable below
X#  or else depend won't work.
X#############################################################################
XMAKEFILE	= Makefile
XRCSDIR		= ./RCS
XCC		= cc
XCFILES		=  main.c format.c xmalloc.c
XOFILES		=  main.o format.o xmalloc.o
XMANFILE		= fmt.1
XPROGRAM		= fmt
X#############################################################################
X# Flags for Installation
X#############################################################################
XBINDIR		= /cn/ua/nagel/bin
XMANDIR		= /cn/ua/nagel/man
XCURSUFFIX	= .1
XMANSUFFIX	= .l
X#############################################################################
X
XLIBS		=  -lm
XDFLAGS		=  -DUCI
XOPTFLAGS	=  -g
XLDFLAGS		=
XCFLAGS		= $(OPTFLAGS) $(DFLAGS)
XLINTFLAGS	=  -bchxz
X
X$(PROGRAM):	$(OFILES)
X	$(CC) $(LDFLAGS) $(OFILES) -o $(PROGRAM) $(LIBS)
X
Xlint:
X	lint $(LINTFLAGS) $(CFILES)
X
Xinstall: $(PROGRAM)
X	install -c -m 755 $(PROGRAM) $(BINDIR)
X
Xinst-man:	$(MANFILE)
X	install -c -m 644 $(MANFILE) $(MANDIR)/`basename $(MANFILE) $(CURSUFFIX)`$(MANSUFFIX)
X
Xinst-all: install inst-man
X
XTAGS: $(CFILES)
X	etags $(CFILES) > TAGS
X
Xtags: $(CFILES)
X	ctags $(CFILES) > tags
X
Xcheckin:
X	-@for i in $(CFILES) $(MANFILE) ; do \
X	    ( if test -f $$i ; then ( echo "Checking in $$i" ; ci -q $$i ) \
X	; fi ) ; done
X
Xcheckout: $(CFILES) $(MANFILE)
X
X$(CFILES) $(MANFILE):
X	co -l -q $@
X
Xclean:
X	rm -f *.o *.out *~ core
X
Xclean-all: clean checkin
X	rm -f $(PROGRAM) tags TAGS
Xdepend:
X	/usr/ucb/mkdep -f $(MAKEFILE) $(CFILES)
X
END_OF_FILE
if test 1690 -ne `wc -c <'Makefile'`; then
    echo shar: \"'Makefile'\" unpacked with wrong size!
fi
# end of 'Makefile'
fi
if test -f 'format.c' -a "${1}" != "-c" ; then
  echo shar: Will not clobber existing file \"'format.c'\"
else
echo shar: Extracting \"'format.c'\" \(10743 characters\)
sed "s/^X//" >'format.c' <<'END_OF_FILE'
X/*****************************************************************************
X *
X * Mark Nagel <nagel@ics.uci.edu>
X * 20 July 1989
X *
X * bool
X * format(fmt, num, buf, buflen)
X *  char *fmt;
X *  double num;
X *  char buf[];
X *  int buflen;
X *
X * The format function will produce a string representation of a number
X * given a _format_ (described below) and a double value.  The result is
X * written into the passed buffer -- if the resulting string is too
X * long to fit into the passed buffer, the function returns false.
X * Otherwise the function returns true.
X *
X * The fmt parameter contains the format to use to convert the number.
X *
X *  #	Digit placeholder.  If the number has fewer digits on either
X *      side of the decimal point than  there are '#' characters in
X *      the format, the extra '#' characters are ignored.  The number
X *      is rounded to the number of digit placeholders as there are
X *      to the right of the decimal point.  If there are more digits
X *      in the number than there are digit placeholders on the left
X *      side of the decimal point, then those digits are displayed.
X *
X *  0	Digit placeholder.  Same as for '#' except that the number
X *      is padded with zeroes on either side of the decimal point.
X *      The number of zeroes used in padding is determined by the
X *      number of digit placeholders after the '0' for digits on
X *      the left side of the decimal point and by the number of
X *      digit placeholders before the '0' for digits on the right
X *      side of the decimal point.
X *
X *  .	Decimal point.  Determines how many digits are placed on
X *      the right and left sides of the decimal point in the number.
X *      Note that numbers smaller than 1 will begin with a decimal
X *      point if the left side of the decimal point contains only
X *      a '#' digit placeholder.  Use a '0' placeholder to get a
X *      leading zero in decimal formats.
X *
X *  %	Percentage.  For each '%' character in the format, the actual
X *      number gets multiplied by 100 (only for purposes of formatting
X *      -- the original number is left unmodified) and the '%' character
X *      is placed in the same position as it is in the format.
X *
X *  ,	Thousands separator.  The presence of a ',' in the format
X *      (multiple commas are treated as one) will cause the number
X *      to be formatted with a ',' separating each set of three digits
X *      in the integer part of the number with numbering beginning
X *      from the right end of the integer.
X *
X *  \	Quote.  This character causes the next character to be
X *      inserted into the formatted string directly with no
X *      special interpretation.
X *
X *  E- E+ e- e+
X *	Scientific format.  Causes the number to formatted in scientific
X *	notation.  The case of the 'E' or 'e' given is preserved.  If
X *      the format uses a '+', then the sign is always given for the
X *	exponent value.  If the format uses a '-', then the sign is
X *	only given when the exponent value is negative.  Note that if
X *	there is no digit placeholder following the '+' or '-', then
X *	that part of the formatted number is left out.  In general,
X *	there should be one or more digit placeholders after the '+'
X *	or '-'.
X *
X *  ;	Format selector.  Use this character to separate the format
X *	into two distinct formats.  The format to the left of the
X *	';' character will be used if the number given is zero or
X *	positive.  The format to the right of the ';' character is
X *      used if the number given is negative.
X *
X *  Any
X *	Self insert.  Any other character will be inserted directly
X *	into the formatted number with no change made to the actual
X *      number.
X *
X *****************************************************************************/
X
X/*****************************************************************************/
X
X#include <stdio.h>
X
X#define bool	int
X#define true	1
X#define false	0
X#define EOS	'\0'
X#define MAXBUF	256
X
Xextern char
X  *strcpy(),
X  *strchr();
X
Xstatic char
X  *fmt_int(),
X  *fmt_frac(),
X  *fmt_exp();
X
Xstatic void
X  reverse();
X
X/*****************************************************************************/
X
Xbool
Xformat(fmt, val, buf, buflen)
X  char *fmt;
X  double val;
X  char *buf;
X  int buflen;
X{
X  register char *cp;
X  char *tmp, *tp, *tmpfmt;
X  bool comma = false, negative = false;
X  char *decimal = NULL;
X  char *exponent = NULL;
X  int exp_val, width;
X  char prtfmt[32];
X  char *mantissa;
X  char *fraction = NULL;
X  int zero_pad = 0;
X
X  if (fmt == NULL)
X    return;
X
X  fmt = tmpfmt = strcpy((char *) xmalloc(strlen(fmt) + 1), fmt);
X  mantissa = (char *) xmalloc(buflen + 1);
X
X  /*
X   * select positive or negative format if necessary
X   */
X  for (cp = fmt; *cp != ';' && *cp != EOS; cp++)
X  {
X    if (*cp == '\\')
X      cp++;
X  }
X  if (*cp == ';')
X  {
X    if (val < 0.0)
X    {
X      val = -val;     /* format should provide sign if desired */
X      fmt = cp + 1;
X    }
X    else
X    {
X      *cp = EOS;
X    }
X  }
X
X  /*
X   * extract other information from format and produce new
X   * malloc'ed format string
X   */
X  tmp = (char *) xmalloc(strlen(fmt) + 1);
X  for (cp = fmt, tp = tmp; *cp != EOS; cp++)
X  {
X    switch (*cp)
X    {
X      case '\\':
X        *tp++ = *cp++;
X        *tp++ = *cp;
X	break;
X
X      case ',':
X        comma = true;
X	break;
X
X      case '.':
X        if (decimal == NULL)
X	  decimal = tp;
X	*tp++ = *cp;
X	break;
X
X      case '%':
X        val *= 100.0;
X	*tp++ = *cp;
X	break;
X
X      default:
X        *tp++ = *cp;
X	break;
X    }
X  }
X  *tp = EOS;
X  xfree(tmpfmt);
X  fmt = tmp;
X
X  /*
X   * extract the exponent from the format if present
X   */
X  for (cp = fmt; *cp != EOS; cp++)
X  {
X    if (*cp == '\\')
X    {
X      cp++;
X    }
X    else if (*cp == 'e' || *cp == 'E')
X    {
X      if (cp[1] == '+' || cp[1] == '-')
X      {
X        tmp = (char *) xmalloc(strlen(cp) + 1);
X	exponent = strcpy(tmp, cp);
X	*cp = EOS;
X	exp_val = 0;
X	while (val < 1.0)
X	{
X          val *= 10.0;
X	  exp_val--;
X	}
X	while (val >= 10.0)
X	{
X	  val /= 10.0;
X	  exp_val++;
X	}
X	break;
X      }
X    }
X  }
X
X  /*
X   * determine maximum decimal places and use sprintf
X   * to build initial character form of formatted value.
X   */
X  width = 0;
X  if (decimal)
X  {
X    *decimal++ = EOS;
X    for (cp = decimal; *cp != EOS; cp++)
X    {
X      switch (*cp)
X      {
X        case '\\':
X          cp++;
X	  break;
X
X        case '#':
X          width++;
X	  break;
X
X	case '0':
X	  zero_pad = ++width;
X	  break;
X      }
X    }
X    zero_pad = strlen(decimal) - zero_pad;
X  }
X  if (val < 0.0)
X  {
X    negative = true;
X    val = -val;
X  }
X  sprintf(prtfmt, "%%.%dlf", width);
X  sprintf(mantissa, prtfmt, val);
X  if ((cp = strchr(mantissa, '.')) != NULL)
X  {
X    fraction = cp + 1;
X    *cp = EOS;
X    cp = fraction + strlen(fraction) - 1;
X    for (; zero_pad > 0; zero_pad--, cp--)
X    {
X      if (*cp == '0')
X        *cp = EOS;
X    }
X  }
X
X  /*
X   * format the puppy
X   */
X  {
X    char *ci, *cf, *ce;
X    int len_ci, len_cf, len_ce;
X    bool ret = false;
X
X    ci = fmt_int(mantissa, fmt, comma, negative);
X    ci = strcpy((char *)xmalloc((len_ci = strlen(ci)) + 1), ci);
X    cf = (fraction) ? fmt_frac(fraction, decimal) : "";
X    cf = strcpy((char *)xmalloc((len_cf = strlen(cf)) + 1), cf);
X    ce = (exponent) ? fmt_exp(exp_val, exponent) : "";
X    ce = strcpy((char *)xmalloc((len_ce = strlen(ce)) + 1), ce);
X    if (len_ci + len_cf + len_ce < buflen)
X    {
X      sprintf(buf, "%s%s%s", ci, cf, ce);
X      ret = true;
X    }
X
X    /*
X     * free up malloc'ed memory
X     */
X    xfree(mantissa);
X    xfree(fmt);
X    if (exponent) xfree(exponent);
X    xfree(ci);
X    xfree(cf);
X    xfree(ce);
X
X    return (ret);
X  }
X}
X
X/*****************************************************************************/
X
Xstatic char *
Xfmt_int(val, fmt, comma, negative)
X  char *val;	    /* integer part of the value to be formatted */
X  char *fmt;	    /* integer part of the format */
X  bool comma;	    /* true if we should comma-ify the value */
X  bool negative;    /* true if the value is actually negative */
X{
X  int digit, f, v;
X  int thousands = 0;
X  char *cp;
X  static char buf[MAXBUF];
X  char *bufptr = buf;
X
X  /*
X   * locate the leftmost digit placeholder
X   */
X  for (cp = fmt; *cp != EOS; cp++)
X  {
X    if (*cp == '\\')
X      cp++;
X    else if (*cp == '#' || *cp == '0')
X      break;
X  }
X  digit = (*cp == EOS) ? -1 : cp - fmt;
X
X  /*
X   * format the value
X   */
X  f = strlen(fmt) - 1;
X  v = (digit >= 0) ? strlen(val) - 1 : -1;
X  while (f >= 0 || v >= 0)
X  {
X    if (f > 0 && fmt[f-1] == '\\')
X    {
X      *bufptr++ = fmt[f--];
X    }
X    else if (f >= 0 && (fmt[f] == '#' || fmt[f] == '0'))
X    {
X      if (v >= 0 || fmt[f] == '0')
X      {
X        *bufptr++ = v < 0 ? '0' : val[v];
X	if (comma && (thousands = (thousands + 1) % 3) == 0 && v > 0)
X	{
X	  *bufptr++ = ',';
X	}
X	v--;
X      }
X    }
X    else if (f >= 0)
X    {
X      *bufptr++ = fmt[f];
X    }
X    if (v >= 0 && f == digit)
X    {
X      continue;
X    }
X    f--;
X  }
X
X  if (negative && digit >= 0)
X    *bufptr++ = '-';
X  *bufptr = EOS;
X  reverse(buf);
X
X  return (buf);
X}
X
X/*****************************************************************************/
X
Xstatic char *
Xfmt_frac(val, fmt)
X  char *val;	    /* fractional part of the value to be formatted */
X  char *fmt;	    /* fractional portion of format */
X{
X  static char buf[MAXBUF];
X  register char *bufptr = buf;
X  register char *fmtptr = fmt, *valptr = val;
X
X  *bufptr++ = '.';
X  while (*fmtptr != EOS)
X  {
X    if (*fmtptr == '\\')
X    {
X      *bufptr++ = *++fmtptr;
X    }
X    else if (*fmtptr == '#' || *fmtptr == '0')
X    {
X      if (*valptr != EOS || *fmtptr == '0')
X      {
X        *bufptr++ = (*valptr != EOS) ? *valptr++ : *fmtptr;
X      }
X    }
X    else
X    {
X      *bufptr++ = *fmtptr;
X    }
X    fmtptr++;
X  }
X  *bufptr = EOS;
X
X  return (buf);
X}
X
X/*****************************************************************************/
X
Xstatic char *
Xfmt_exp(val, fmt)
X  int val;	    /* value of the exponent */
X  char *fmt;	    /* exponent part of the format */
X{
X  static char buf[MAXBUF];
X  register char *bufptr = buf;
X  char valbuf[64];
X  bool negative = false;
X
X  *bufptr++ = *fmt++;
X  if (*fmt++ == '+')
X    *bufptr++ = (val < 0) ? '-' : '+';
X  else if (val < 0)
X    *bufptr++ = '-';
X  *bufptr = EOS;
X
X  if (val < 0)
X  {
X    val = -val;
X    negative = true;
X  }
X  sprintf(valbuf, "%d", val);
X
X  strcat(buf, fmt_int(valbuf, fmt, false, negative));
X  return (buf);
X}
X
X/*****************************************************************************/
X
Xstatic void
Xreverse(buf)
X  register char *buf;
X{
X  register char *cp = buf + strlen(buf) - 1;
X  register char tmp;
X
X  while (buf < cp)
X  {
X    tmp = *cp;
X    *cp-- = *buf;
X    *buf++ = tmp;
X  }
X}
X
X/*****************************************************************************/
X
END_OF_FILE
if test 10743 -ne `wc -c <'format.c'`; then
    echo shar: \"'format.c'\" unpacked with wrong size!
fi
# end of 'format.c'
fi
if test -f 'main.c' -a "${1}" != "-c" ; then
  echo shar: Will not clobber existing file \"'main.c'\"
else
echo shar: Extracting \"'main.c'\" \(447 characters\)
sed "s/^X//" >'main.c' <<'END_OF_FILE'
X#include <stdio.h>
X
Xmain()
X{
X  double number;
X  char fmt[1024], buf[10];
X  int i;
X
X  while (!feof(stdin))
X  {
X    printf("Number? "); fflush(stdout);
X    if (!gets(buf)) break;
X    sscanf(buf, "%lf", &number);
X    printf("Format? "); fflush(stdout);
X    if (!gets(fmt)) break;
X    if (!format(fmt, number, buf, sizeof(buf)))
X    {
X      for (i = 0; i < sizeof(buf) - 1; i++)
X        buf[i] = '*';
X      buf[i] = '\0';
X    }
X    puts(buf);
X  }
X}
END_OF_FILE
if test 447 -ne `wc -c <'main.c'`; then
    echo shar: \"'main.c'\" unpacked with wrong size!
fi
# end of 'main.c'
fi
if test -f 'xmalloc.c' -a "${1}" != "-c" ; then
  echo shar: Will not clobber existing file \"'xmalloc.c'\"
else
echo shar: Extracting \"'xmalloc.c'\" \(675 characters\)
sed "s/^X//" >'xmalloc.c' <<'END_OF_FILE'
X/*
X * A safer saner malloc, for careless programmers
X * $Revision: 6.1 $
X */
X
X#include <stdio.h>
X#include <curses.h>
X
Xextern char *malloc();
X
X#ifdef SYSV3
Xextern void free();
Xextern void exit();
X#endif
X
Xchar *
Xxmalloc(n)
Xunsigned n;
X{
Xregister char *ptr;
X
Xif ((ptr = malloc(n + sizeof(double))) == NULL)
X    fatal("xmalloc: no memory");
X*((int *) ptr) = 12345;		/* magic number */
Xreturn(ptr + sizeof(double));
X}
X
Xxfree(p)
Xchar *p;
X{
Xif (p == NULL)
X    fatal("xfree: NULL");
Xp -= sizeof(double);
Xif (*((int *) p) != 12345)
X    fatal("xfree: storage not malloc'ed");
Xfree(p);
X}
X
Xfatal(str)
Xchar *str;
X{
X/*    deraw(); */
X    (void) fprintf(stderr,"%s\n", str);
X    exit(1);
X}
END_OF_FILE
if test 675 -ne `wc -c <'xmalloc.c'`; then
    echo shar: \"'xmalloc.c'\" unpacked with wrong size!
fi
# end of 'xmalloc.c'
fi
echo shar: End of shell archive.
exit 0
--
Mark Nagel
UC Irvine Department of ICS   +----------------------------------------+
ARPA: nagel@ics.uci.edu       | Defend your right to arm bears.        |
UUCP: ucbvax!ucivax!nagel     +----------------------------------------+