1

I have this:

#include <iostream>
#include <iomanip> 

std::string ExampleInstance::RoundNumber(float result) {

    std::string RoundResult;

    std::cout << std::fixed << std::showpoint;
    std::cout << std::setprecision(1);
    std::cout << result << std::endl;

    RoundResult = std::to_string(result);
    return RoundResult;
}

I want to pass this method a float, round it to one decimal place, convert it to a string and then return it. Currently this doesn't do anything to the number.

Would setPrecision be more effective? I'm new to C++.

halfer
  • 19,824
  • 17
  • 99
  • 186
Dan
  • 2,304
  • 6
  • 42
  • 69

1 Answers1

2

You can use ostringstream for this purpose. Not forget to include <sstream>.

Code snippet:

string RoundNumber(float result)
{
    std::ostringstream out;
    out<<std::setprecision(1)<<std::fixed<<std::showpoint<< result;
    std::string RoundResult =  out.str();
    return RoundResult;
}
ashiquzzaman33
  • 5,781
  • 5
  • 31
  • 42