Dev Tool Tips/C/C++2013. 8. 16. 16:29

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


typedef struct temporary_number_s
{
    char buffer[32];
    char offset;
    char length;
} temporary_number_t;

char * formatNumber(long long num)
{
    static temporary_number_t source, destination;
    int    is_comma_position=0;
    int commas=0;
    int i=0;

    memset(&destination, 0, sizeof(temporary_number_t));

    /* -999 ~ 999 */
    if (num > -1000 && num < 1000 )
    {
        sprintf(destination.buffer, "%ld", num);
        return destination.buffer;
    }

    memset(&source, 0, sizeof(temporary_number_t));
    sprintf(source.buffer, "%ld", num);
    source.length = strlen(source.buffer); /* source.l is bigger than 3 */

    if(num<0)
        commas=(source.length-2)/3; /* exclude '-' character */
    else
        commas=(source.length-1)/3;

    destination.length = source.length + commas;

    destination.offset= destination.length-1;
    source.offset = source.length-1;

    is_comma_position=0;

    while (source.offset>-1)
    {
        destination.buffer[destination.offset] = source.buffer[source.offset];
        destination.offset--;
        source.offset--;

        is_comma_position++;

        if (is_comma_position == 3 && commas)
        {
            commas--;
            destination.buffer[destination.offset] = ',';
            destination.offset--;
            is_comma_position = 0;
        }
    }
    return destination.buffer;
}

int main(int argc, char **argv)
{
    printf("%s ... %s\n", argv[1], formatNumber(atol(argv[1])));
    return 0;
}

Posted by young.h.rhie