It's not simple for a novice programmer. :)

> -----Original Message-----
> From: Dennis [mailto:[EMAIL PROTECTED]
> Sent: Friday, January 31, 2003 5:45 AM
> To: [email protected]
> Subject: Re: Adding Commas
> 
> 
> On Thu, 30 Jan 2003, stormpunk wrote:
> 
> > I made one up real quick, I see no problems.
> >
> > --
> >  >test commas
> > 1:1
> > 1200:1,200
> > 10200:10,200
> > -10200:-10,200
> > 123123123:123,123,123
> > 2123123123:2,123,123,123
> > -2123123123:-2,123,123,123
> 
> Stormpunk, there's a small bug in your code with 3, 6, and 9 digit
> negative numbers.
> -100:-,100
> -100000:-,100,000
> -100000000:-,100,000,000
> 
> 
> 
> I was bored and decided to write my own functions to do this.
> 
> The first one does pretty much the same thing as stormpunk's:
> let sprintf format the number, then stick commas in it.
> 
> The second one does all the number to string conversion itself,
> adding in commas during the process.
> 
> These functions have the same usage as stormpunk's.
> 
> Who said this wasn't simple?  :)
> 
> 
> Dennis
> 
> 
> 
> char * comma(long d, char * buf)
> {
>       char buf1[14];
>       int len;
>       int i = 0, j = 0;
> 
>       /* convert the number to a string */
>       len = sprintf(buf1, "%ld", d);
> 
>       /* copy any leading - over */
>       if (buf1[0] == '-')
>       {
>               buf[i++] = buf1[j++];
>       }
> 
>       /* Copy the first digit */
>       buf[i++] = buf1[j++];
> 
>       while (j < len)
>       {
>               /* insert a , if necessary */
>               if (((len - j) % 3) == 0)
>                       buf[i++] = ',';
> 
>               /* copy one digit */
>               buf[i++] = buf1[j++];
>       }
> 
>       /* NUL terminate the string */
>       buf[i] = '\0';
> 
>       return buf;
> }
> 
> char * comma(long d, char * buf)
> {
>       int i = 0;
>       long base = 1000000000;
>       int digits = 10;
> 
>       /* take care of negative numbers */
>       if (d < 0)
>       {
>               buf[i++] = '-';
>               d *= -1;
>       }
> 
>       /* take care of 0 */
>       if (d == 0)
>               buf[i++] = '0';
> 
>       /* no leading 0's */
>       while (base > d)
>       {
>               base = base / 10;
>               digits--;
>       }
> 
>       while (base >= 1)
>       {
>               /* Get one number */
>               buf[i++] = d / base + '0';
> 
>               /* Update the variables */
>               d %= base;
>               base = base / 10;
>               --digits;
> 
>               /* add in the , for thousands */
>               if ((digits % 3) == 0 && digits > 0)
>                       buf[i++] = ',';
>       }
> 
>       /* NUL terminate the string */
>       buf[i] = '\0';
> 
>       return buf;
> }
> 
> 
> 
> -- 
> ROM mailing list
> [email protected]
> http://www.rom.org/cgi-bin/mailman/listinfo/rom
> 

Reply via email to