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

Recommended Answers

All 4 Replies

Member Avatar for jencas

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.

Oh thats right!
Thanks a bunch!

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

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() ;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.