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.
Note
If you want to store the number in scientific notation in stream, you can do
stream << scientific;
For fixed point format, do
stream << fixed;
7 Comments |
C++, VC++ 2005 | Tagged: how to round a float, remove decimals from a number, Round a number, round decimal places, round off float, round off number |
Permalink
Posted by cppkid
January 29, 2009
I had the habit of using [] operator to access elements of a map. For example, if we have
map<int, int> myMap, to get the element corresponding to 10, we can use
myMap[10]. This is perfectly ok as long as we have an element corresponding to 10. But, what if we don’t have one corresponding to 10?
There lies the problem. In this situation, myMap is already added with a default elemnent corresponding to 10 ([] operator provides no facility to validate if an element exists) and in the above situation, it is 0. As a result, a new (unwanted) element is added to the map (we can see that the size of map has been incremented by 1).
So a better alternative is to use the find() function associated with map. It does not add an element and if the element is not found, it will return map::end().
The example given below illustrates this.
#include <map>
#include <iostream>
using namespace std;
int main()
{
map myMap;
cout << "Size of myMap = " << myMap.size() << '\n'; // will be 0
int content = myMap[0];
// Now the size of myMap will be 1 as we used the [] operator
// and the value of content = myMap[0] = 0
cout << "Size of myMap = " << myMap.size() << '\n';
// Instead, if we use find, the size will not change.
// It will look for the element only.
map::const_iterator it = myMap.find(1);
// Here the element has not been found. So it = myMap.end()
cout << "Size of myMap = " << myMap.size() << '\n'; // will be 1 only
return 0;
}
So the best practice is to avoid [] operator for accessing individual elements of a map.
10 Comments |
C++, VC++ 2005 | Tagged: access element of a map, get element of a map, map in C++, map issue, problem with map, stl map, [] for map |
Permalink
Posted by cppkid