显示用C分隔的整数逗号

显示用C分隔的整数逗号

This question already has answers here:
Closed 6 years ago.
How to format a number from 1123456789 to 1,123,456,789 in C?
(19个答案)
如何显示用C分隔的整数逗号?
例如,如果int i=9876543,则结果应为9,876,543.

最佳答案

您可以使用LC_NUMERICsetlocale()或构建自己的函数,例如:

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

char *fmt(long x)
{
    char s[64], *p = s, *q, *r;
    int len;

    len = sprintf(p, "%ld", x);
    q = r = malloc(len + (len / 3) + 1);
    if (r == NULL) return NULL;
    if (*p == '-') {
        *q++ = *p++;
        len--;
    }
    switch (len % 3) {
        do {
            *q++ = ',';
            case 0: *q++ = *p++;
            case 2: *q++ = *p++;
            case 1: *q++ = *p++;
        } while (*p);
    }
    *q = '\0';
    return r;
}

int main(void)
{
    char *s = fmt(9876543);

    printf("%s\n", s);
    free(s);
    return 0;
}

关于c - 显示用C分隔的整数逗号? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18610016/

10-11 22:08