Convert strings to floating point with decimal and decimal point support

How to convert a string to a floating point number if I want both commas to be interpreted as decimal point, and dot to be interpreted as decimal point?

The code analyzes text files created by our customers. They sometimes use decimal points, and sometimes decimal points, but not thousands of separators.

+4
source share
3 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 deal with thousands separators, it will be much more difficult.

+8
source

Just find the decimal point ',' and convert it to '.' , 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 the C string instead of std::string , use strchr from <cstring> to change the original string (remember to change it or work with a copy of the locale if you need the original version).

+3
source

If you want to do this as part of a regular reading of std::istream , you will create your own facet std::num_get<...> , put it in the std::locale object and set it to your stream using imbue() (or setting std::locale as a global locale before creating the stream).

0
source

Source: https://habr.com/ru/post/1398565/


All Articles