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;
March 1, 2009 at 4:54 pm
Just passing by.Btw, your website have great content!
_________________________________
Making Money $150 An Hour
May 21, 2009 at 9:18 pm
Пора переименовать блог, присвоив название связанное с доменами
может хватит про них?
May 23, 2009 at 5:23 am
Пора переименовать блог, присвоив название связанное с доменами
может хватит про них?
May 24, 2009 at 3:18 am
Даже и не придирешься!
May 26, 2009 at 1:39 pm
Спасибо за пост. Позновательно.
October 18, 2009 at 10:54 pm
Занятно. Хотелось бы еще чего-нибудь об этом же.
October 31, 2009 at 3:46 am
Действительно, на самом деле все очень просто