I don’t know of an easy way in C to print a number with commas, yet large numbers are very common, and very hard to read without commas. This routine converts a long int to a string and inserts commas. It can be called multiple times within a subroutine call without overwriting the returned string.

/*
 *================================================================
 * Convert a (possibly very large) number to a string with commas every
 * three digits.  This can be called up to LNC_RETURNS times within a
 * single printf or other function.  Positive and negative numbers are
 * okay.
 *
 * This will need changes for localization.
 * Thanks to Judy for improved algorithm.
 *----------------------------------------------------------------
 */

char*
Lib_numberComma(
    long n)			// IN: number to be comma-ized
{
#define LNC_RETURNS 9		// max times called within one function
#define LNC_MAXSIZE 32		// maximum size of a stringized long int

    int		 commas;	// # of commas to insert.
    char*	 char_move_p;	// Move chars around.
    int		 digits;	// # of digits in the number.
    int		 digits_sign;	// # of digits plus 1 if negative.
    char*	 return_p;
    static void* ss_id = NULL;

    // Convert the number to a string.
    return_p = Lib_ss(&ss_id, LNC_RETURNS, LNC_MAXSIZE);
    sprintf(return_p, "%ld", n);

    // How many commas will we need to insert?
    digits_sign = strlen(return_p);
    digits = digits_sign;
    if (*return_p == '-') {
	// ...ignoring any "-" sign.
	digits--;
    }
    commas = (digits - 1) / 3;

    // Make sure we have an appropriately-placed NUL.
    char_move_p = return_p + digits_sign - 1;	// Point at last char.
    *(char_move_p + commas + 1) = '\0';

    // Move characters over and insert commas.
    for (; commas > 0; commas--) {
	*(char_move_p + commas) = *char_move_p; char_move_p--;
	*(char_move_p + commas) = *char_move_p; char_move_p--;
	*(char_move_p + commas) = *char_move_p; char_move_p--;
	*(char_move_p + commas) = ',';
    }

    return return_p;
}


[Back to home page]