千分位显示整数

来源:互联网 发布:淘宝客 余杭区法院 编辑:程序博客网 时间:2024/04/28 21:14

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

/*copy from http://m.blog.csdn.net/article/details?id=8681982make 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;}
原创粉丝点击