I am trying to switch for example: input 54321.987, then 4 and 2 should switch, so output would be 52341.987. 54321.777 should become 52341.777. If it is 2345.777 it should
Using string manipulation:
char string[20];
snprintf(string, sizeof(string), "%09.3f", x);
char *dot = strchr(string, '.');
assert(dot != 0 && dot > string + 4);
char old_4 = dot[-4];
char old_2 = dot[-2];
dot[-2] = old_4;
dot[-4] = old_2;
/* If you need a float back */
sscanf(string, "%lf", &x);
Using arithmetic manipulation:
double frac_part;
double int_part;
frac_part = modf(x, &int_part);
long value = int_part;
int dig_2 = (int_part / 10) % 10;
int dig_4 = (int_part / 1000) % 1000;
assert(dig_4 != 0);
value -= 10 * dig_2 + 1000 * dig_4;
value += 10 * dig_4 + 1000 * dig_2;
int_part = value;
x = int_part + frac_part;
Neither sequence of operations is minimal, but they are fairly straight-forward.
I just wrote this:
double swapDigits(double in)
{
return in + ((int)(in / 10) % 10 - (int)(in / 1000) % 10) * 990.0;
}
First, you have to determine these digits.
You can do so with
double tens = ((int)(x / 10)) % 10;
double thousands = ((int)(x / 1000)) % 10;
which enables you to do
x = x - (tens * 10.0) - (thousands * 1000.0) + (tens * 1000.0) + (thousands * 10.0);
which subtracts them at their original place and re-adds them in a swapped way.
You can optimize this to
x = x + tens * (1000.0 - 10.0) - thousands * (1000.0 - 10.0);
and, again, this to
x += (tens - thousands) * 990.0;