这个问题在这里已有答案:
我们如何在C中显示分隔的整数逗号?
例如,如果int i=9876543
,结果应该是9,876,543.
你可以玩LC_NUMERIC
和setlocale()
或建立自己的功能,如:
#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;
}
我相信没有内置功能。但是,您可以将整数转换为字符串,然后根据结果字符串的长度计算逗号位置(提示:第一个逗号将在strlen(s)%3
数字之后,避免使用逗号)。