我有一个浮点变量,格式为xxxxxxxx.xx(例如11526.99)。我想用逗号将其打印为11,562.99。如何在C中插入逗号?
答案 0 :(得分:2)
尝试:
#include <locale.h>
#include <stdio.h>
int main()
{
float f = 12345.67;
// obtain the existing locale name for numbers
char *oldLocale = setlocale(LC_NUMERIC, NULL);
// inherit locale from environment
setlocale(LC_NUMERIC, "");
// print number
printf("%'.2f\n", f);
// set the locale back
setlocale(LC_NUMERIC, oldLocale);
}
这取决于当前的语言环境。 C和POSIX语言环境没有千位分隔符。您可以将自己设置为您知道使用千位分隔符的区域设置,而不是从环境继承区域设置。在我的系统上,使用"en_NZ"
提供了一个千位分隔符。
答案 1 :(得分:0)
下面的 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
假定转换为字符串的浮点数不会超过49个字符(怀疑增加MAX
)char *a = addcommas(3.1415) ; char *b = addcommas(2.7182) ;
中的