千分位显示整数

转自:把长的数字用逗号隔开显示(千分位)

/*
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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值