math question, padding + rounding

Hi,

I’m trying to replicate the function nf() from processing (http://processing.org/reference/nf-.html). i just want to be able to pass in a value & required decimal places and have a string returned.

eg.
float n = 7;
nf(n, 2);
outputs- 7.00

or

float n = 7.1234;
nf(n, 2);
outputs- 7.12

Thanks in advance.

  
  
float n = 7.1234;  
cout << ofToString(n, 2);  
  

Thanks Kyle, solved the main problem. Kind of related, I noticed that ofToString automatically rounds to 4 places for floats/doubles when you don’t set the precision, do you know how to convert a double to a string and preserve the decimal places?

eg.
double latitude = -33.952267;
string s = ofToString(latitude);

// s returns “-33.9523” but should be “-33.952267”

If I used ofToString(latitude, 6). This would add extra 0’s even if their were less decimal places - ofToString(30.123) would return “30.123000”?

you can read more about stringstream formatting at http://www.cplusplus.com/reference/iostream/manipulators/setprecision/

i think what you want is to use neither fixed nor scientific, which is the default. maybe this would work:

  
  
template <class T>  
string ofToStringAdaptive(const T& value, int precision){  
	ostringstream out;  
	out << setprecision(precision) << value;  
	return out.str();  
}  
  

this way setprecision acts like a maximum instead of adding padding.

perfect! reading from that link you posted, the default formatting includes digits before the decimal point as well… interesting. i think this might just work for latitude + longitude values, as there is a maximum of 9 digits for values (including before the decimal point).

thanks again kyle.