Jan 102011

This is a small function that will format a number to string that contains commas.  It’s function is to make the numbers easier to read before displaying them.  One nice feature with this function is it creates the string with the formatting based on the current locale being used by the application.  Simple, but useful.

PTCHAR Comma(LONGLONG value,PTCHAR bufout, UINT nSize)
	TCHAR bufin[30]; // 30 digits is a really big number
	TCHAR dsep[5], tsep[5];
	fmt.NumDigits = 0;
	fmt.LeadingZero = _ttoi(bufin);
	fmt.Grouping = 3;
	fmt.lpDecimalSep = dsep;
	fmt.lpThousandSep = tsep;
	fmt.NegativeOrder = _ttoi(bufin); 

	_stprintf_s(bufin, _T("%I64d"), value);
	::GetNumberFormat(LOCALE_USER_DEFAULT, 0, bufin, &fmt, bufout, nSize);
	return bufout;

For example, it could be used to fill in a subitem in a list control:

m_cList.SetItemText(nItem,2,Comma(nValue, buf, 29));

Leave a Reply