Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Digit grouping in C's printf

I wish to output large numbers with thousand-separators (commas or spaces) — basically the same as in How to display numeric in 3 digit grouping but using printf in C (GNU, 99).

If printf does not support digit grouping natively, how can I achieve this with something like printf("%s", group_digits(number))?

It must support negative integers and preferably floats, too.

like image 363
Gnubie Avatar asked May 15 '12 14:05

Gnubie


2 Answers

If you can use POSIX printf, try

#include <locale.h>
setlocale(LC_ALL, ""); /* use user selected locale */
printf("%'d", 1000000);
like image 160
pmg Avatar answered Nov 16 '22 08:11

pmg


Here is a compact way of doing it:

// format 1234567.89 -> 1 234 567.89
extern char *strmoney(double value){
    static char result[64];
    char *result_p = result;
    char separator = ' ';
    size_t tail;

    snprintf(result, sizeof(result), "%.2f", value);

    while(*result_p != 0 && *result_p != '.')
        result_p++;

    tail = result + sizeof(result) - result_p;

    while(result_p - result > 3){
        result_p -= 3;
        memmove(result_p + 1, result_p, tail);
        *result_p = separator;
        tail += 4;
    }

    return result;
}

For example, a call to strmoney(1234567891.4568) returns the string "1 234 567 891.46". You can easily replace the space with another separator (such as a comma) by changing the separator variable at the top of the function.

like image 3
Erick Ringot Avatar answered Nov 16 '22 09:11

Erick Ringot