测试:输入:1234568
输出:1,234,568
输入:-12345689
输出:-12,345,689
char *int2str_withcommas(long number){
char *result_str = (char *)malloc(sizeof(char)*20);
int iNumCount = 0,iComma = 0,iStrlen = 0,iHead = 0; //iNumCount是数字个数,iComma是逗号个数,iStrlen是字符串长度,不包括结尾空格,iHead是结头位置
long fabsNumber = fabs(number); //取绝对值便于处理。
long tmp = fabsNumber;
//计算数字的个数
while (tmp > 0) {
tmp /= 10;
iNumCount ++;
}
//计算需要多少个逗号
iComma= iNumCount/3;
//计算字符串长度
if (number < 0) {
iStrlen = iNumCount + 1 + iComma;
result_str[0] = '-';
}else iStrlen = iNumCount + iComma;
//每三位为一块,iHead是每块头位置的字符位置(倒序)
//并且在字符串后边补上'\0'
iHead = iStrlen;
result_str[iStrlen] = '\0';
//关键部分
while (iStrlen >= 1&&fabsNumber >0) {
if ((iHead-iStrlen) ==3) {
result_str[iStrlen-1] = ',';
iStrlen--;
iHead -=4;
}
result_str[iStrlen-1] = fabsNumber%10 + '0';
fabsNumber /= 10;
iStrlen --;
}
return result_str;
}