Search code examples
cdoubleswapdigits

Swap digits in a double in C


What I want to do in C is swap two digits in a double.

For example, if the input is 54321.987 and I want to swap the 2nd with the 4th digit, the output should be 52341.987.

Example when too small: 12.34 would output 1002.34.


Solution

  • Using stringification approach:
    There are more elegant ways, but you can see the steps (and improve on) this pseudo code to stringify, move values, and convert back to number.

    char buf1[20];
    char buf2[20];
    char *dummy;
    double val = 54321.987;
    
    sprintf(buf1, "%9.3f", val );
    //Now the number is in string form: "54321.987".  Just move the two elements  
    buf2[0]=buf1[0];
    buf2[1]=buf1[3];
    buf2[2]=buf1[2];
    buf2[3]=buf1[1]; //and so on
    //now convert back:
    
    val = strtod(buf2, &dummy);
    printf("%9.3f\n", val);
    

    Or, a function could be used to do essentially the same thing: (still stringification)

    double swap_num_char(double num, int precision, int c1, int c2); //zero index for c1 and c2
    
    
    int main(void)
    {
    
        double val = 54321.987;
    
        printf("%9.3f\n", swap_num_char(val, 3, 1, 3));
    
        return 0;   
    }
    
    double swap_num_char(double num, int precision, int c1, int c2)
    {
        char buf[25]; 
        char format[10];
        char *dummy;
        char c;
    
        sprintf(format, "%s0.%df", "%", precision);
    
        sprintf(buf, format, num);
    
        c = buf[c1];
        buf[c1] = buf[c2];
        buf[c2] = c;
    
        num = strtod(buf, &dummy);
    
        return num;
    }