Maintaining float precision string parsing

Hi,

So I have a project where I’m parsing lots of floats from a csv with the great ofxCsv addon.

Once I have my numbers as std::string, ex: “-706482,4243618”, the floats are formatted with a comma separator.

I have a simple function that replaces the comma with a dot. i.e.,

float formatNum(const string & s){
	float ret = -1;
	size_t pos = s.find(",");
	if(pos == s.npos){ cout << "no dot formatNum"; return ret; }

	string numstr = s;
	numstr.replace(pos, 1, ".");

	return ofToFloat(numstr);
}

The number this function outputs is something like -70648.4243

Do you have an idea to get the full number on the string instead of this truncated working example?

Thanks

i’d try ofToDouble instead

thanks & just tried, but I’m getting exactly equivalent results with float or double data types

perhaps using python to do the parsing?

for this example i can live with this precision loss (gps coords), would be nice to know if someone already dove into big numbers and keeping exact precison under c++. yeah, i’m aware of mantissa and exponents float/double precision. perhaps boost bignumbers?

cheers

have you changed the type of the return value of the function? if you use ofToDouble but then return float you’ll loose precision again

of course I have changed :slight_smile:

	// float 				latitude;
	// float 				longitude;
	// float 				height;
	double 				latitude;
	double 				longitude;
	double 				height;


	double formatNum(const string & s){
		float ret = -1;
		size_t pos = s.find(",");
		if(pos == s.npos){ ofLog() << "no dot formatNum"; return ret; }

		string numstr = s;
		numstr.replace(pos, 1, ".");

		// return 0.0f;
		return ofToDouble(numstr);

	}

It seems this is just a problem of how c++ outputs floats/doubles by default, the number you are getting should be correct, is only when showing it in the console that appears with less precision.

try:

std::cout << std::setprecision(15) << ofToFloat(numstr) << std::endl;

should work as well with ofLog

You are right, now the full number get logged in the console.

Thanks