954,500 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Rounding function

Hello,
I am trying to solve an assignment in a book.
It is asking me to write a program that takes a positive number with fractional part, which would round it to two decimal places. For example, 3.4256 to 3.43. Now, the thing that confuses me is that this past chapter talked about functions and a little bit about strings. My question is if there is a separate function that does it or is it related to strings somehow?
Thank you for your help

grisha83
Junior Poster in Training
70 posts since Sep 2008
Reputation Points: 36
Solved Threads: 0
 

Write a function that takes a float or double as parameter and returns a string. Let the function format the return string. Maybe a printf() or stringstream is useful.

jencas
Posting Whiz
366 posts since Dec 2007
Reputation Points: 395
Solved Threads: 71
 

Oh thats right!
Thanks a bunch!

grisha83
Junior Poster in Training
70 posts since Sep 2008
Reputation Points: 36
Solved Threads: 0
 

Another question:
how do i tell the string the rounding criteria?
For example, 2.5632 is rounded to 2.56, while 2.5652 is 2.57.
Any kind of help will be appreciated

grisha83
Junior Poster in Training
70 posts since Sep 2008
Reputation Points: 36
Solved Threads: 0
 

perhaps the easiest way is to use the iostream formatted output facilities:

#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>

int main()
{
  double a = 2.5632, b = 2.5652 ;

  std::ostringstream strout ;
  strout << std::fixed << std::showpoint << std::setprecision(2)
         << "a: " << a << "  b: " << b << '\n' ;

  std::cout << strout.str() ;
}
vijayan121
Posting Virtuoso
1,606 posts since Dec 2006
Reputation Points: 1,159
Solved Threads: 287
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You