Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,870 questions

51,793 answers

573 users

How to convert a string with either , or . as decimal/thousand separators into a float in C

1 Answer

0 votes
#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

*/



 



answered Jun 27, 2025 by avibootz
...