How do you use setprecision() when declaring a double variable in C++?

Viewed 46

So I'm trying to learn more about C++ and I'm practicing by making a calculator class for the quadratic equation. This is the code for it down below.

#include "QuadraticEq.h"
 
string QuadraticEq::CalculateQuadEq(double a, double b, double c)
{
    double sqrtVar = sqrt(pow(b, 2) - (4 * a * c));
    double eqPlus = (-b + sqrtVar)/(2 * a);
    double eqMinus = (-b - sqrtVar) / (2 * a);
    return "Your answers are " + to_string(eqPlus) + " and " + to_string(eqMinus);
}

I'm trying to make it so that the double variables eqPlus and eqMinus have only two decimal points. I've seen people say to use setprecision() but I've only seen people use that function in cout statements and there are none in the class because I'm not printing a string out I'm returning one. So what would I do here? I remember way before learning about some setiosflags() method, is there anything I can do with that?

1 Answers

You can use stringstream instead of the usual std::cout with setprecision().

#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>

std::string adjustDP(double value, int decimalPlaces) {
    // change the number of decimal places in a number
    std::stringstream result;
    result << std::setprecision(decimalPlaces) << std::fixed << value;
    return result.str();
}
int main() {
    std::cout << adjustDP(2.25, 1) << std::endl; //2.2
    std::cout << adjustDP(0.75, 1) << std::endl; //0.8
    std::cout << adjustDP(2.25213, 2) << std::endl; //2.25
    std::cout << adjustDP(2.25, 0) << std::endl; //2
}

However, as seen from the output, this approach introduces some rounding off errors when value cannot be represented exactly as a floating point binary number.

Related