C语言版:
#include<stdio.h>
#include<string.h>
#include<stdarg.h>
void longToStr(long l,char* buf)
{
char str[20];
int len;
int index;
int offset=0;
sprintf(str,"%d",l); //转为字符串
len = strlen(str);
memset(buf,0,20);
strncat(buf,str+offset,len%3);
offset +=len%3;
if((len%3)&&(len>3))
{
strcat(buf,",");//插入逗号
}
for(index = len-3; index > 0; index -= 3)
{
strncat(buf,str+offset,3);
offset +=3;
if(index/3)
{
strcat(buf,",");//插入逗号
}
}
strcat(buf,str+offset);
}
void floatToStr(float f,char* buf)
{
char str[20];
int len;
int index;
int offset=0;
sprintf(str,"%.2f",f); //转为字符串
len = strlen(str) - 3;
memset(buf,0,20);
strncat(buf,str+offset,len%3);
offset +=len%3;
if((len%3)&&(len >3))
{
strcat(buf,",");//插入逗号
}
for(index = len-3; index > 0; index -= 3)
{
strncat(buf,str+offset,3);
offset +=3;
if(index/3)
{
strcat(buf,",");//插入逗号
}
}
strcat(buf,str+offset);
}
int main()
{
long l = 1234567890;
float f = 12345678.56;
char buf[20];
longToStr(l,buf);
printf("%s\n",buf);
floatToStr(f,buf);
printf("%s\n",buf);
return 0;
}
C++版:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
long l;
cin>>l;
string str;
str = to_string(l); //转为字符串
size_t len = str.length();
for(int index =(int) len-3; index > 0; index -= 3)
str.insert(index, ",");//插入逗号。
cout<<str<<endl;//输出结果。
return 0;
}