Home > other >  How can I convert an int (which represents an decimal without its decimal places) to a double in c?
How can I convert an int (which represents an decimal without its decimal places) to a double in c?

Time:02-12

I need to convert integers (which represents decimals but without using decimal places) to doubles in C. I know how many decimal places the integer should have because this information is also there. This new double is handed over to a JSON-API which appends this to a JSON structure afterwards.

Example: I need to produce a double value of 255.89 for an input of int1 := 25589 and int2 := 2

I've written this function:

cJSON* addDecimalToJSON(cJSON* const object, const char * const name, const int number, const int decimals) {
    double d = number;
    for(int i = 0; i < decimals; i  ) {
        d = d / 10;
    }
    return addNumberToObject(object, name, d);
}

This works for some values and in the JSON structure is the correct decimal value representation, but for other values (like the example above) the result is a "255.89000000000001".

After trial and error I'm at this point:

double test = 25589;
test = test / 10;
test = test / 10;
cout << test << endl;
-> 255.89
double test2 = 255.89;
cout << (test == test2) << endl;
-> 0
cout << (test2 == 255.89) << endl;
-> 1

If I put test to the JSON API it still produces "255.89000000000001". If I put test2 to the JSON API it produces "255.89". So there must be any kind of precision problem which is "carried" into the API (but which gets cut off from cout function so I cant 'see' it). What I need in the end is the desired decimal value of "255.89" without the precision problem. How can this be achieved?

CodePudding user response:

The addNumberToObject doesn't let you control how many significant digits you want to print.

You can get around this by using sprintf to format the number yourself and adding it as a string.

cJSON* addDecimalToJSON(cJSON* const object, const char * const name, 
                        const int number, const int decimals) {
    double d = number;
    for(int i = 0; i < decimals; i  ) {
        d = d / 10;
    }
    char dstr[50];
    sprintf(dstr,"%.*f", decimals, d);
    return addStringToObject(object, name, dstr);
}
  •  Tags:  
  • c
  • Related