下面的 addcommas 函数是一个版本 locale-less,它允许负浮点数(但不适用于像 3.14E10 这样的指数)
#include <stdio.h>
#include <string.h>
#define DOT '.'
#define COMMA ','
#define MAX 50
static char commas[MAX]; // Where the result is
char *addcommas(float f) {
char tmp[MAX]; // temp area
sprintf(tmp, "%f", f); // refine %f if you need
char *dot = strchr(tmp, DOT); // do we have a DOT?
char *src,*dst; // source, dest
if (dot) { // Yes
dst = commas+MAX-strlen(dot)-1; // set dest to allow the fractional part to fit
strcpy(dst, dot); // copy that part
*dot = 0; // 'cut' that frac part in tmp
src = --dot; // point to last non frac char in tmp
dst--; // point to previous 'free' char in dest
}
else { // No
src = tmp+strlen(tmp)-1; // src is last char of our float string
dst = commas+MAX-1; // dst is last char of commas
}
int len = strlen(tmp); // len is the mantissa size
int cnt = 0; // char counter
do {
if ( *src<='9' && *src>='0' ) { // add comma is we added 3 digits already
if (cnt && !(cnt % 3)) *dst-- = COMMA;
cnt++; // mantissa digit count increment
}
*dst-- = *src--;
} while (--len);
return dst+1; // return pointer to result
}
如何调用它,例如(main例子)
int main () {
printf ("%s\n", addcommas(0.31415));
printf ("%s\n", addcommas(3.1415));
printf ("%s\n", addcommas(31.415));
printf ("%s\n", addcommas(314.15));
printf ("%s\n", addcommas(3141.5));
printf ("%s\n", addcommas(31415));
printf ("%s\n", addcommas(-0.31415));
printf ("%s\n", addcommas(-3.1415));
printf ("%s\n", addcommas(-31.415));
printf ("%s\n", addcommas(-314.15));
printf ("%s\n", addcommas(-3141.5));
printf ("%s\n", addcommas(-31415));
printf ("%s\n", addcommas(0));
return 0;
}
编译指令示例
gcc -Wall comma.c -o comma
在做
./comma
应该输出
0.314150
3.141500
31.415001
314.149994
3,141.500000
31,415.000000
-0.314150
-3.141500
-31.415001
-314.149994
-3,141.500000
-31,415.000000
0.000000
- 将
DOT 设置为点
- 将
COMMA 设置为应为逗号的内容
-
MAX 设置为 50 假定转换为字符串的浮点数不会超过 49 个字符(增加 MAX 有疑问)
- 从作为参数给出的 float 返回指向 commas 添加的字符串的指针,指向静态区域的指针,因此
-
addcommas 不是reentrant,并且返回的指针所指向的值(通常)在每次调用后都会改变,例如。
- in
char *a = addcommas(3.1415) ; char *b = addcommas(2.7182) ; a 在第二次调用 addcommas 后无法再安全使用