Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String to floating point conversion with support for both decimal point and decimal comma

Tags:

c++

How do I convert a string to a floating point number if I want both comma interpreted as decimal comma and point interpreted as decimal point?

The code parses text files that have been created by our customers. They sometimes use decimal points and sometimes decimal commas but never thousand separators.

like image 782
Johan Råde Avatar asked Feb 27 '12 08:02

Johan Råde


2 Answers

Use std::replace to do the hard work:

#include <cstdlib>
#include <string>
#include <algorithm>

double toDouble(std::string s){
    std::replace(s.begin(), s.end(), ',', '.');
    return std::atof(s.c_str());
}

If you need to cope with thousands separators it'd be much more tricky.

like image 107
James Avatar answered Oct 05 '22 23:10

James


Just search for the decimal comma ',' and convert it to a '.', then use atof from <cstdlib>:

#include <cstdlib>
#include <cstdio>
#include <string>

double toDouble(std::string s){
    // do not use a reference, since we're going to modify this string
    // If you do not care about ',' or '.' in your string use a 
    // reference instead.
    size_t found = s.find(",");
    if(found != std::string::npos)
        s[found]='.'; // Change ',' to '.'
    return std::atof(s.c_str());
}

int main(){
    std::string aStr("0.012");
    std::string bStr("0,012");

    double aDbl = toDouble(aStr);
    double bDbl = toDouble(bStr);

    std::printf("%lf %lf\n",aDbl,bDbl);
    return 0;    
}

If you use a C string instead of std::string use strchrfrom <cstring> to change your original string (don't forget to change it back or work on a locale copy if you need the original version afterwards).

like image 23
Zeta Avatar answered Oct 05 '22 23:10

Zeta