Search code examples
cdoublefloor

Shorten double value x digit


I have a double value and I want to shorten it to 6 digits after the integer part. For example:

double aDouble = 418.73684210526318;
double convertedDouble = conversion (aDouble); 

convertedDouble must be 418.736842

I implemented this solution:

convertedDouble = floor(aDouble * 1000000) / 1000000;

However, convertedDouble is 418.73684200000002, not 418.73684200000000

What can I do?


Solution

  • The simplest solution to the decision tree problem you mention in comments would be to think in terms of the range of doubles that should go to a particular branch of the tree, rather than a single double.

    However, here is an attempt at the conversion function you asked for:

    double conversion(double in){
        char wkStr[1000];
        snprintf(wkStr, sizeof(wkStr), "%.6f", in);
        double result;
        sscanf(wkStr, "%lf", &result);
        return result;
    }
    

    As you have discovered, finding the double closest to the result of rounding a given double to a limited number of decimal places is not a trivial problem. It can be treated as the combination of two non-trivial but already solved problems:

    1. Format the input double as a decimal string rounded to the required number of decimal places.
    2. Parse that string to get the closest double to the rounded decimal value.