commify a number

50 views
Skip to first unread message

Sam Steingold

unread,
May 15, 1995, 3:00:00 AM5/15/95
to
Hi,
Before writing a function to convert a number to a comma-separated
string, I want to be sure there is no library function doing that.
In a recent thread in alt.sources someone mentioned function ltocs(),
but it is not mentioned in the UNIX man pages (nor in the gnu info), so
it probably doesn't exist.
SO: is there a function
char * name (int)
that returns string "2,234,000" for input 2234000.
Thanks!
(for cops out there: this is NOT a homework).

--
<A HREF="http://www.math.ucla.edu/~shteingd"> Sam Steingold </A>
I would appreciate comments on / corrections of my English from native
English speakers. Thank You!

Warren Porter

unread,
May 20, 1995, 3:00:00 AM5/20/95
to
05/19/95 07:05 pm

SSłFrom: shte...@math.ucla.edu (Sam Steingold)

SSłBefore writing a function to convert a number to a comma-separated
SSłstring, I want to be sure there is no library function doing that.

I saved this from a few years ago:
From: TONY TORTORELLI Number: 5723 [51] C-Language
Subj: FORMATTING NUMBERS Status: Public

ÍÍŻHmm.. Why doesn't someone just write a function for this, and post it so
ÍÍŻwe can add it to our .LIB's?

Because someone already has!

For those of you who missed it (with credit to Larry Hudson):


/*****************************************************************************
* commify() *
* *
* Commify a number, that is add commas between every third digit ahead of *
* the decimal point. Rounds off to abs(round) digits following the *
* decimal point. Stores the results into the buf[] passed to the function *
* and returns a pointer to it. Uses the standard library function fcvt() *
* to do the conversion from the double val to the string of digits. *
* *
*****************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *commify(double val, char *buf, int round)
{
static char *result;
char *nmr;
int dp, sign;

result = buf;
if(round < 0) /* Be sure round-off is positive */
round = -round;
nmr = fcvt(val, round, &dp, &sign); /* Convert number to a string */
if(sign) /* Prefix minus sign if negative */
*buf++ = '-';
if(dp <= 0){ /* Check if number is less than 1 */
if(dp < -round) /* Set dp to max(dp, -round) */
dp = -round;
*buf++ = '0'; /* Prefix with "0." */
*buf++ = '.';
while(dp++) /* Write zeros following decimal */
*buf++ = '0'; /* point */
}
else{ /* Number is >= 1, commify it */
while(dp--){
*buf++ = *nmr++;
if(dp % 3 == 0)
*buf++ = dp ? ',' : '.';
}
}
strcpy(buf, nmr); /* Append rest of digits */
return result; /* following dec pt */
}
---
ţ SPEED 1.30 #1672 ţ Paradigms: Shift Happens

Reply all
Reply to author
Forward
0 new messages