Search code examples
c++approximation

How to do 2 decimal digit approximation in C++?


I would like to do approximation in my code here.

Here is my code:

#include <iomanip>
#include <iostream>

int main()
{
    double num1 = 123.455;
    std::cout << std::fixed << std::showpoint;
    std::cout << std::fixed << std::showpoint;
    std::cout << std::setprecision(2);
    std::cout << num1 << std::endl;
    return 0;
}

What I want:

123.46
Process returned 0 (0x0)   execution time : 0.284 s
Press any key to continue.

Actual Result:

123.45
Process returned 0 (0x0)   execution time : 0.284 s
Press any key to continue.

I'm sure that I need to use setprecision, but what do I still need to add to successfully get the desired output?


Solution

  • #include <cmath>

    std::round(num1*100.0)/100.0

    should do the trick.