[CODE]Formatting numbers with commas

From: Peter Ajamian (peter@pajamian.dhs.org)
Date: 01/21/01

I recently wrote this little function that I use to format integers with
commas when displaying them, I thought that someone here might benefit
from it.

First arg is the number to be formatted, it is defined as a long so that
it will work with anything up to a 32 bit integer, anythign less than a
long should work fine because it will be implicitly cast to a long for
the function.

Second arg can either be a buffer of at least 15 characters to hold the
result or NULL.  If NULL is passed as the second arg format_comma will
use it's own internal buffer.  Note that this same buffer is re-used for
each call to format_comma where NULL is passed as the second argument,
so you can only use it once per sprintf (or similar function).  If you
need to use it more than once then you will have to pass your own buffer
as the second arg (a different buffer is required for each call).

char *format_comma(long number, char *retval)
  static char ret_buf[15]; /* "-2,147,483,648\0" = 15 chars */
  char buf[15] = "";
  int sign = 1;

  if (!retval)

  if (!number)
    return "0";

  if (number < 0) {
    sign = -1;
    number *= -1;

  while (number / 1000) {
    sprintf(retval, ",%03ld%s", number % 1000, buf);
    strcpy(buf, retval);
    number /= 1000;

  sprintf(retval, "%ld%s", number * sign, buf);

  return retval;

An example of usage in a stock function:

 void get_check_money(struct char_data * ch, struct obj_data * obj)
   int value = GET_OBJ_VAL(obj, 0);

   if (GET_OBJ_TYPE(obj) != ITEM_MONEY || value <= 0)


   GET_GOLD(ch) += value;

   if (value == 1)
     send_to_char("There was 1 coin.\r\n", ch);
   else {
-    sprintf(buf, "There were %d coins.\r\n", value);
+    sprintf(buf, "There were %s coins.\r\n", format_comma(value, NULL));
     send_to_char(buf, ch);

Please credit me if you use it.
Have Fun!

Regards, Peter

   | FAQ: http://qsilver.queensu.ca/~fletchra/Circle/list-faq.html |
   | Archives: http://post.queensu.ca/listserv/wwwarch/circle.html |

This archive was generated by hypermail 2b30 : 12/03/01 PST