65.9K
CodeProject is changing. Read more.
Home

XFormatNumber - A function to format numbers with commas

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.59/5 (9 votes)

Jun 26, 2002

CPOL

1 min read

viewsIcon

72663

downloadIcon

1053

An easy-to-use function that provides locale-correct comma-formatting of numbers

Introduction

Formatting of numeric values with commas looks nice, but sometimes commas are not the correct thousands separator - many countries use "." for thousands separator. To ensure the correct separator, the Win32 function GetNumberFormat() should be used. However, this API requires the setup of a decimal separator, thousands separator, digit grouping, etc., which can add many lines of code to do a simple thing.

After needing to use GetNumberFormat() one more time, I decide to make a simple function with defaults taken from the locale.

XFormatNumber Features

XFormatNumber takes as input a numeric string, which may or may not contain decimal point and fractional digits. XFormatNumber is defined as

CString XFormatNumber(LPCTSTR lpszNumber, int nFracDigits)
The parameter lpszNumber is numeric string, and the nFracDigits parameter specifies whether to include fractional digits in the  returned CString: 0 means no fractional digits, >0 means return nFracDigits fractional digits, and -1 means return however many fractional digits are contained in the numeric string.

XFormatNumber Demo

The demo app shows results for various formatting options:

m_List.AddString(XFormatNumber(_T("1"), -1));
m_List.AddString(XFormatNumber(_T("10"), -1));
m_List.AddString(XFormatNumber(_T("100"), -1));
m_List.AddString(XFormatNumber(_T("1000"), -1));
m_List.AddString(XFormatNumber(_T("10000"), -1));
m_List.AddString(XFormatNumber(_T("100000"), -1));
m_List.AddString(XFormatNumber(_T("1000000"), -1));
m_List.AddString(XFormatNumber(_T("10000000"), -1));
m_List.AddString(XFormatNumber(_T("100000000"), -1));
m_List.AddString(XFormatNumber(_T("1000000000"), -1));
m_List.AddString(XFormatNumber(_T("1000.0"), -1));
m_List.AddString(XFormatNumber(_T("1000.00"), -1));
m_List.AddString(XFormatNumber(_T("1000.000"), -1));
m_List.AddString(XFormatNumber(_T("1000.0000"), -1));
m_List.AddString(XFormatNumber(_T("1000.00000"), 1));

XFormatNumber Screenshot

Usage

This software is released into the public domain. You are free to use it in any way you like. If you modify it or extend it, please to consider posting new code here for everyone to share. This software is provided "as is" with no expressed or implied warranty. I accept no liability for any damage or loss of business that this software may cause.