/*
copy from http://m.blog.csdn.net/article/details?id=8681982
make a little modify
*/
std::string int2str_withcommas(int64_t number)
{
std::string result_str;
//'digit_num' specifies the num of digits
//'comma_num' specifies the num of commas
//'str_len' specifies the length of the string
//'head\tail' specifies the flag of the algorithm
unsigned int digit_num = 0, comma_num = 0, str_len = 0, head = 0, tail = 0;
int64_t fabsNumber = fabs(number);
int64_t tmp = fabsNumber;
//calculate the num of digits
do {
digit_num++;
tmp /= 10;
} while (tmp > 0);
//calculate the num of commas
comma_num = (digit_num-1) / 3;
//calculate the length of the string
if (number < 0) {
str_len = digit_num + 1 + comma_num;
result_str.resize(str_len);
result_str[0] = '-';
tail = 2;
} else {
str_len = digit_num + comma_num;
result_str.resize(str_len);
tail = 1;
}
//treat per three letters as a block
head = str_len;
// result_str[str_len] = '\0';
//main algorithm
while (str_len >= tail/* && fabsNumber > 0*/) {
if ((head - str_len) == 3) {
result_str[str_len - 1] = ',';
str_len--;
head -= 4;
}
result_str[str_len - 1] = fabsNumber % 10 + '0';
fabsNumber /= 10;
str_len--;
}
return result_str;
}
千分位显示整数
最新推荐文章于 2022-09-15 11:46:53 发布