kiran kumar
kiran kumar

Reputation: 153

Convert string to double variable which is seperated by a comma(0,07)

In C++ I've got a double variable to be read which is seperated by a comma(0,07).I am first reading it a string from an excel and trying to converting it into a double.

string str = "0,07"; // Actually from Excel.
double number = strtod(str .c_str(), NULL);
double number1 = atof(str .c_str());
cout << number<<endl;
cout <<number1<<endl;

Both of them return 0 as output instead of 0.07. can someone explain me how to convert double to 0.07 instead of 0.

Upvotes: 3

Views: 4053

Answers (4)

sergej
sergej

Reputation: 17999

You can use:

std::replace(str.begin(), str.end(), ',', '.'); // #include <algorithm>

to replace the comma by a dot before converting.

Working example:

#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
    string str = "0,07"; // Actually from Excel.
    replace(str.begin(), str.end(), ',', '.');

    double number = strtod(str.c_str(), NULL);
    double number1 = atof(str.c_str());
    cout << number << endl;
    cout << number1 << endl;

   return 0;
}

Upvotes: -1

songyuanyao
songyuanyao

Reputation: 172934

You can define a customized numeric facet (numpunct) for it:

class My_punct : public std::numpunct<char> {
protected:
    char do_decimal_point() const {return ',';}//comma
};

and then use a stringstream and locale with it:

stringstream ss("0,07");
locale loc(locale(), new My_punct);
ss.imbue(loc);
double d;
ss >> d;

DEMO

Upvotes: 3

Emilio Garavaglia
Emilio Garavaglia

Reputation: 20730

The problem is that the default locale is the "C" (for "Classic"), that uses '.' as decimal separator, while excel use the one of the OS. that is most likely the one of a lain language.

You can either:

  • ask the originator of the data to export with an english-like locale
  • set in your program a locale based on std::locale("")(so that your program work with the system locale -admitting they are the same, see http://en.cppreference.com/w/cpp/locale/locale)
  • set you program with a latin-based locale (IT, or ES, for example)
  • ignore locales and replace the ","-s in the string with "."-s before try to interpret it as number. (see std::replace)

Upvotes: 2

Arkhan
Arkhan

Reputation: 109

Would this be fine ?

#include <string>
#include <iostream>

using namespace std;

int main()
{
     string str = "0,07"; // Actually from Excel.
     int index = str.find(',');
     str.replace(index, index+1, '.');

     double number = stod(str);

     cout << number << endl;

     return 0;
}

PS: stod is a c++11 function, but you need to use it instead of stof if you want to keep the double precision. Otherwise number should be a float

Upvotes: -1

Related Questions