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.
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.
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 strchr
from <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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With