Is there a direct function to set the decimal of number. For example I got 3.14341
and my parameter is 2
, so I get 3.14
. There is a function setprecision
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 123.120000
instead of 123.12
.
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.