关于数字分组 (123456789.99 => 123,456,789.99)

Sandrer 2010-09-01 11:09:49
请问有没有效率高点的分组算法?
...全文
189 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
Sandrer 2011-08-31
  • 打赏
  • 举报
回复
呵呵,很久没来了

当时等不了答案,自己写了一个~

void FormatNumber(double dblNumber, LPTSTR pszText, int nMaxCount)
{
ASSERT(pszText != NULL);
ASSERT(nMaxCount > 0);

if (dblNumber < 1000.00f)
{
::_stprintf(pszText, _T("%.2f"), dblNumber);
return;
}

LPTSTR lpszBuffer = new TCHAR[nMaxCount];
::memset(lpszBuffer, 0, sizeof(TCHAR) * nMaxCount);
::_stprintf(lpszBuffer, _T("%.2f"), dblNumber);

int nTextLen = ::lstrlen(lpszBuffer);
int nIntLen = nTextLen - 3;
int nSection = nIntLen / 3;
nSection += (nIntLen % 3) == 0 ? -1 : 0;
int nCounter = 0;
int j = nTextLen;
int nNewLen = nTextLen + nSection;
if (nMaxCount < nNewLen)
return;

for (int i = nTextLen - 1; i >= 0; i--)
{
nCounter++;

if ((nCounter % 3) == 0 && lpszBuffer[i] != '.')
{
pszText[i + nSection] = lpszBuffer[--j];
if ((i + nSection - 1) < 0)
break;
pszText[i + --nSection] = ',';
nCounter = 0;
}
else
{
pszText[i + nSection] = lpszBuffer[--j];
}
}

pszText[nNewLen] = '\0';

delete[] lpszBuffer;
}
justkk 2010-09-02
  • 打赏
  • 举报
回复
/***********************************************
函数描述:转换double值为以千分符','分隔的字符串
参数说明:double 数值
int 结果小数点后位数(<=8)
***********************************************/
justkk 2010-09-02
  • 打赏
  • 举报
回复
很早的时候写过一个函数
char * dcomma(double d, int n)
{
int i, j,
flag = 0; /* 整数部分 */
char *p, t[50];

static char s[50];

if( n > 8 ) n = 8;
else if( n < 0 ) n = 0;
if( n == 0 ) flag = 1;

s[sizeof(s) - 1] = 0;

sprintf(t, "%.*lf", n, d);
p = t + strlen(t) - 1;

for( i = sizeof(s) - 1, j = 0; p - t >= 0; p-- )
{
if( flag == 1 ) j++;
else if( *p == '.' ) flag = 1;

s[i--] = *p;
if( j == 3 && p - t && *(p-1) != '-' )
{
j = 0;
s[i--] = ',';
}
}

return(s + i + 1);
}
Sandrer 2010-09-02
  • 打赏
  • 举报
回复
看标题,就是把一串数字进行分组
例如:123456789.99 分组后变为 123,456,789.99
toma2008 2010-09-01
  • 打赏
  • 举报
回复
不知什么意思,帮顶下

3,881

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 其它技术问题
社区管理员
  • 其它技术问题社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧