Digit grouping in C's printf

2019-05-15 07:43发布

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.

7条回答
别忘想泡老子
2楼-- · 2019-05-15 08:20

My own version for unsigned int64:

char* toString_DigitGrouping( unsigned __int64 val )
{
    static char result[ 128 ];
    _snprintf(result, sizeof(result), "%lld", val);

    size_t i = strlen(result) - 1;
    size_t i2 = i + (i / 3);
    int c = 0;
    result[i2 + 1] = 0;

    for( ; i != 0; i-- )
    {
        result[i2--] = result[i];
        c++;
        if( c % 3 == 0 )
            result[i2--] = '\'';
    } //for

    return result;  
} //toString_DigitGrouping
查看更多
登录 后发表回答