0

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.

juanferrer
  • 1,192
  • 1
  • 16
  • 29
Cihan Kara
  • 47
  • 10
  • Why do you want to round the number internally. Normally you only need to round it when you display it. Normally there is not a need to get rid of precision. If you are working with something like currency then you should be using integers/a fixed precision library. – NathanOliver Apr 19 '17 at 13:20
  • This is my task in company and numbers should be sent with strings thanks for the answer – Cihan Kara Apr 19 '17 at 13:23
  • This can be achieved with a `std::stringstream` and manipulators such as `std::fixed` and `std::setprecision`. However, you might want to consider manipulating the string directly. Using an intermediate `float` risks damaging your precision. – François Andrieux Apr 19 '17 at 13:23
  • Possible duplicate of [Digit limitation from decimal point in C++](http://stackoverflow.com/questions/798046/digit-limitation-from-decimal-point-in-c) – juanferrer Apr 19 '17 at 14:49

2 Answers2

0

Fool of me. The answer is as simple as this. I did a lot of things needlessly...

 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;
 }
juanferrer
  • 1,192
  • 1
  • 16
  • 29
Cihan Kara
  • 47
  • 10
-1

not exactly, but you can set the precision using std::setprecision

define a method:

void printWithPrecision(const double value, unsigned decimalPlaces)
{
    std::cout << "A Double with " << decimalPlaces <<" decimal places: "<<std::setprecision(decimalPlaces) << value << std::endl;
}

and call it like:

double d = 7987.12354689765416;

for (auto x = 0; x<10; x++)
{
    printWithPrecision(d, x);
}

dont forget to include the input-output-manipulator:

#include <iomanip>
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97