0

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

3
Contributors
4
Replies
5
Views
9 Years
Discussion Span
Last Post by vijayan121
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.

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

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() ;
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.