Skip site navigation (1)Skip section navigation (2)
Date:      Fri, 2 Feb 2001 04:05:54 -0800 (Pacific Standard Time)
From:      Joseph Stein <joes@joescanner.com>
To:        <freebsd-questions@freebsd.org>
Subject:   Formatting a number
Message-ID:  <Pine.WNT.4.31.0102020402460.920-100000@hood>

next in thread | raw e-mail | index | archive | help

A few weeks ago, I posted a question asking how to format a number.  I
couldn't find a solution (however I am still certain there is an easier
way than what I finally hacked out)...

Here was the solution I came up with in case anybody else wants it.  It is
pretty rudimentary, but it works.

/*
 * fmtnbr.c
 *
 * Input: a number (string)
 * Output: A formatted number
 *
 * Copyright (C) 2001, Joseph Stein (joes@joescanner.com)
 *
 * Permisson to use this code is granted to anybody.  If you
 * include it in other code, please give me credit.
 */

#include <stdio.h>

int main(int argc, char* argv[]) {
   int numlen;
   int i;
   int j;
   int remainder;
   char teststr[256];

   if (argc!=2) {
      fprintf(stderr,"Usage:\n\t%s <number>\n\n", argv[0]);
      return(2);
   }


   strcpy(teststr, argv[1]);

   numlen=strlen(teststr);
   teststr[numlen]='\0';
   remainder=numlen%3;

#ifdef DEBUG
   fprintf(stderr,"number %s is %d digits.\n", teststr, numlen);
#endif

   if (numlen<4) {
      printf("%s", teststr);
      exit(1);
   }

   if (remainder==0) {
#ifdef DEBUG
      fprintf(stderr,"multiple of 3\n");
#endif
      for (i=0; i<numlen;) {
         for (j=0; j<3; j++) {
            printf("%c",teststr[i++]);
         }
         printf("%s", i!=numlen ? "," : "");
      }
   } else {
#ifdef DEBUG
      fprintf(stderr,"not an even multiple of three\n");
#endif
      for (i=0; i<remainder;) {
         printf("%c",teststr[i++]);
      }
      printf(",");
      for (i=0+remainder; i<numlen;) {
         for (j=0; j<3; j++) {
            printf("%c",teststr[i++]);
         }
         printf("%s", i!=numlen ? "," : "");
      }
   }
   return(0);
}




To Unsubscribe: send mail to majordomo@FreeBSD.org
with "unsubscribe freebsd-questions" in the body of the message




Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?Pine.WNT.4.31.0102020402460.920-100000>