How To Round Off A Number

February 18, 2009

Sometimes, it is needed to round off a number to some decimal digits.  Again stringstream comes to help us with the aid of iomanip function setprecision. Following is a sample function to round off a number to a fixed digits.

double Round(const double value, const int digits)
   stringstream stream;
   // Store the number with required no. of decimal
   // places to stream
   stream << setprecision(digits) << value;
   // Convert stream to number
   double roundedValue = 0.0;
   stream >> roundedValue;
   return roundedValue;

The header files sstream and iomanip are needed for the above.

Please note that the variable value holds the number with original no. of decimal places and digits is the total number of digits needed (including the non-decimal digits) after rounding has taken place.

Round(10.37665, 3) gives 10.4 and Round(10.3745, 4) gives 10.37.


If you want to store the number in scientific notation in stream, you can do

stream <<  scientific;

For fixed point format, do

stream <<  fixed;


How To Set Extra Data With Each Row Of A List Box

February 3, 2009

We can associate a 32 bit value with each row of a list box. The member function SetItemData() of CListBox can be used for this purpose.

The syntax is

int SetItemData(
   int nIndex,
   DWORD_PTR dwItemData


  • nIndex – Zero based row index of the list box
  • dwItemData – 32 bit value to be stored in the row

The return value will be LB_ERR, if an error occurs.
The stored value can be retrieved using CListBox::GetItemData(). Again, the syntax is

DWORD_PTR GetItemData(
   int nIndex
) const;

where nIndex is the zero based index of the list box row, from where we have to get the data.

An example is given below.

for (int index = 0; index < myListBox->GetCount(); ++index)
   if (myListBox->GetItemData(index) == DWORD(-1))
      myListBox->SetItemData(index, 0);

The header file afxwin.h is needed for the above functions.