I wrote this function to recursively round a double
to N digits:
double RoundDouble(double value, unsigned int digits)
{
if (value == 0.0)
return value;
string num = dtos(value);
size_t found = num.find(".");
string dec = "";
if (found != string::npos)
dec = num.substr(found + 1);
else
return value;
if (dec.length() <= digits)
{
LogToFile("C:\\test.txt", "RETURN: " + dtos(value) + "\n\n\n");
return value;
}
else
{
double p10 = pow(10, (dec.length() - 1));
LogToFile("C:\\test.txt", "VALUE: " + dtos(value) + "\n");
double mul = value * p10;
LogToFile("C:\\test.txt", "MUL: " + dtos(mul) + "\n");
double sum = mul + 0.5;
LogToFile("C:\\test.txt", "SUM: " + dtos(sum) + "\n");
double floored = floor(sum);
LogToFile("C:\\test.txt", "FLOORED: " + dtos(floored) + "\n");
double div = floored / p10;
LogToFile("C:\\test.txt", "DIV: " + dtos(div) + "\n-------\n");
return RoundDouble(div, digits);
}
}
But as from the log file, something really strange is happening with floor() in some cases...
Here's an output example of good calculation:
VALUE: 2.0108
MUL: 2010.8
SUM: 2011.3
FLOORED: 2011
DIV: 2.011
-------
VALUE: 2.011
MUL: 201.1
SUM: 201.6
FLOORED: 201
DIV: 2.01
-------
RETURN: 2.01
And here's an output example of bad calculation:
VALUE: 67.6946
MUL: 67694.6
SUM: 67695.1
FLOORED: 67695
DIV: 67.695
-------
VALUE: 67.695
MUL: 6769.5
SUM: 6770
FLOORED: 6769 <= PROBLEM HERE
DIV: 67.69
-------
RETURN: 67.69
Isn't floor(6770) supposed to return 6770? Why is it returning 6769?
So first of all thanks everyone for the suggestions. Btw for the moment the "double to string -> string to double -> floor" solution seems to be the only one giving exactly the expected result. So i just needed to replace:
double floored = floor(sum);
with
double floored = floor(stod(dtos(sum)));
If anyone has a better solution please post it.