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];
	NUMBERFMT fmt;
	fmt.NumDigits = 0;
	::GetLocaleInfo(LOCALE_USER_DEFAULT,LOCALE_ILZERO,bufin,2);
	fmt.LeadingZero = _ttoi(bufin);
	fmt.Grouping = 3;
	::GetLocaleInfo(LOCALE_USER_DEFAULT,LOCALE_SDECIMAL,dsep,4);
	fmt.lpDecimalSep = dsep;
	::GetLocaleInfo(LOCALE_USER_DEFAULT,LOCALE_STHOUSAND ,tsep,4);
	fmt.lpThousandSep = tsep;
	::GetLocaleInfo(LOCALE_USER_DEFAULT,LOCALE_INEGNUMBER ,bufin,2);
	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

(required)

(required)