I have a function that takes a double and truncates it to a specified
number of decimal places. I've found that I have to add a small
number to the input value otherwise I get errors due to the way
floating points work.
double TruncateToDigits(double dValue, int iDigitsToRightOfDecimal)
{
double dEpsilon = 1e-8;
// high limit, about 100,000,000 for this epsilon (1e-8)
// low limit, about 7 decimal places for this epsilon (1e-8)
// modifying it will increase one limit while reducing the other
ASSERT(fabs(dValue) < 100000000.0);
ASSERT(iDigitsToRightOfDecimal <= 7);
int iSignFactor = (dValue >= 0.0 ? 1 : -1);
dValue *= iSignFactor; // make positive
dValue += dEpsilon; // make it error towards the positive
double dMulti = pow(10.0, iDigitsToRightOfDecimal);
dValue *= dMulti; // move valid digits left of decimal
dValue = floor(dValue); // truncate to whole value
dValue /= dMulti; // move digits back
dValue *= iSignFactor; // put sign back
return dValue;
}
This appears to work, however it only reliably works within a certain
range, as listed in the comments.
Is there a better way to do this? One that would work for any
floating point range?