Cihan Kara Cihan Kara - 2 years ago 85
C++ Question

set decimal numbers according to parameter

Is there a direct function to set the decimal of number. For example I got


and my parameter is
, so I get
. There is a function
but it only prints the result. Also, I made an algorithm like this:

std::string fixPrecision(std::string const& value, int digits)
std::string num = value;
float temp = std::stof(num);
float fractpart, intpart;
fractpart = modf(temp, &intpart);
int a = (int)(fractpart * pow(10,digits));
double last = intpart + a*(pow(0.1 , digits));
return std::to_string(last);

It works well. I get what I want but I have to convert it to string so the result is
instead of

I could sure use some help here. Thanks in advance.

Edit: It is not a duplicate question because my function needs to take integer and return numbers with string format. Thanks again.

Answer Source

fool of me.. the answer is as simple as this. i did a lot of things needless...

 std::string fixPrecision(std::string const& value, int digits)
 auto pos = value.find(".");
 if(pos != std::string::npos)
 return value.substr(0, pos+digits+1);
 return value;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download