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

1 Answer

0 votes
#include <iostream>
#include <iomanip>
#include <string>
#include <algorithm>

double toFloat(const std::string& input) {
    std::string str = input;

    int commaCount = std::count(str.begin(), str.end(), ',');
    int dotCount = std::count(str.begin(), str.end(), '.');

    if (commaCount && dotCount) {
        if (str.find_last_of(',') > str.find_last_of('.')) {
            str.erase(std::remove(str.begin(), str.end(), '.'), str.end());
            std::replace(str.begin(), str.end(), ',', '.');
        } else {
            str.erase(std::remove(str.begin(), str.end(), ','), str.end());
        }
    } else if (commaCount) {
        str.erase(std::remove(str.begin(), str.end(), '.'), str.end());
        std::replace(str.begin(), str.end(), ',', '.');
    } else {
        str.erase(std::remove(str.begin(), str.end(), ','), str.end());
    }

    return std::stod(str);
}

int main() {
    double value = toFloat("1,224,533.533");
    std::cout << std::fixed << std::setprecision(3) << value << std::endl; 
    
    value = toFloat("1.224.533,533");
    std::cout << std::fixed << std::setprecision(3) << value << std::endl; 
    
    value = toFloat("2.354,67");
    std::cout << std::fixed << std::setprecision(2) << value << std::endl; 
    
    value = toFloat("2,354.67");
    std::cout << std::fixed << std::setprecision(2) << value << std::endl; 
}



/*
run:

1224533.533
1224533.533
2354.67
2354.67

*/

 



answered Jun 27 by avibootz
...