
Introduction
While working on a project I needed to display the sizes in a human readable format, i.e. 1KB, 1.20MB, and so on. Although I am referring to this functionality here as file size formatting, the same code can
be used to format any value that represents a number of bytes. Due to the simplicity of the problem, I decided that this would be a perfect topic for my first article!
Requirements
- Using B, KB, MB, GB to display the sizes in a logical format.
- Using commas as thousands separator
An example would be: 1,023 KB (if size = 1023 * 1024 bytes)
Using the code
The code is composed of two functions. The first is InsertSeparators()
which is used internally from within the main function to add the thousands separator. The second and main function is FormatSize()
which is used to do the all the
required formatting.
Following is the code for InsertSeparators()
. This function is placed in an unnamed namespace in order to make it a local function.
namespace
{
CString InsertSeparator (DWORD dwNumber)
{
CString str;
str.Format("%u", dwNumber);
for (int i = str.GetLength()-3; i > 0; i -= 3)
{
str.Insert(i, ",");
}
return (str);
}
}
Following is the code for the FormatSize()
function:
CString FormatSize (DWORD dwFileSize)
{
static const DWORD dwKB = 1024;
static const DWORD dwMB = 1024 * dwKB;
static const DWORD dwGB = 1024 * dwMB;
DWORD dwNumber, dwRemainder;
CString strNumber;
if (dwFileSize < dwKB)
{
strNumber = InsertSeparator(dwFileSize) + " B";
}
else
{
if (dwFileSize < dwMB)
{
dwNumber = dwFileSize / dwKB;
dwRemainder = (dwFileSize * 100 / dwKB) % 100;
strNumber.Format("%s.%02d KB", (LPCSTR)InsertSeparator(dwNumber), dwRemainder);
}
else
{
if (dwFileSize < dwGB)
{
dwNumber = dwFileSize / dwMB;
dwRemainder = (dwFileSize * 100 / dwMB) % 100;
strNumber.Format("%s.%02d MB", InsertSeparator(dwNumber), dwRemainder);
}
else
{
if (dwFileSize >= dwGB)
{
dwNumber = dwFileSize / dwGB;
dwRemainder = (dwFileSize * 100 / dwGB) % 100;
strNumber.Format("%s.%02d GB", InsertSeparator(dwNumber), dwRemainder);
}
}
}
}
strNumber.Replace(".00", "");
return strNumber;
}
Future Improvements
The following are planned future improvements for the next versions of the article:
- Make the thousands separator and the decimal point dependent on Control Panel settings.
- Unicode Support
History
Edit History
2 Dec 2002 - Initial Edit