vendredi 12 juillet 2019

Prevent over-rounding happening in C++ doubles

Have googled a lot about avoiding rounding errors but none of them are solving my case. Need to round off 9.99999975e-05 upto 8 or more precision.

Have tried using stringstream along with setprecision which is pretty much the standard way according to other answers on this site.

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

using namespace std;

int main(void){

    double val = 9.99999975e-05;
    stringstream tmp;
    tmp << setprecision(8) << fixed << val;
    cout << tmp.str();
    return 0;

}

Ideally I would like the result to be 0.00009999 But I am getting 0.00010000 , which I believe is occurring due to rounding off from farthest to most significant '9'.

Any idea how can I stop rounding at 8th precision ?

Aucun commentaire:

Enregistrer un commentaire