#include <stdio.h>
#include <string.h>
#include <stdlib.h> // strtod
double toFloat(const char* input) {
char str[128];
strncpy(str, input, sizeof(str));
str[sizeof(str) - 1] = '\0';
int commaCount = 0, dotCount = 0;
for (int i = 0; str[i]; i++) {
if (str[i] == ',') commaCount++;
else if (str[i] == '.') dotCount++;
}
char* lastComma = strrchr(str, ',');
char* lastDot = strrchr(str, '.');
if (commaCount && dotCount) {
if (lastComma > lastDot) {
// ',' is decimal, '.' is thousand
char temp[128] = "";
for (int i = 0; str[i]; i++) {
if (str[i] != '.')
strncat(temp, (str[i] == ',') ? "." : (char[]){str[i], '\0'}, 2);
}
strcpy(str, temp);
} else {
// '.' is decimal, ',' is thousand
char temp[128] = "";
for (int i = 0; str[i]; i++) {
if (str[i] != ',')
strncat(temp, (char[]){str[i], '\0'}, 2);
}
strcpy(str, temp);
}
} else if (commaCount) {
// Assume ',' is decimal
char temp[128] = "";
for (int i = 0; str[i]; i++) {
if (str[i] == '.') continue;
else if (str[i] == ',') strncat(temp, ".", 2);
else strncat(temp, (char[]){str[i], '\0'}, 2);
}
strcpy(str, temp);
} else {
// Only '.' or clean string
char temp[128] = "";
for (int i = 0; str[i]; i++) {
if (str[i] != ',')
strncat(temp, (char[]){str[i], '\0'}, 2);
}
strcpy(str, temp);
}
return strtod(str, NULL); // convert a string to a double
}
int main() {
printf("%.3f\n", toFloat("1,224,533.533"));
printf("%.3f\n", toFloat("1.224.533,533"));
printf("%.2f\n", toFloat("2.354,67"));
printf("%.2f\n", toFloat("2,354.67"));
return 0;
}
/*
run:
1224533.533
1224533.533
2354.67
2354.67
*/