TITLE: converting doubles to strings with precision (Newsgroups: comp.lang.c++.moderated, 24 Sept 96) KANZE: kanze@gabi-soft.fr (J. Kanze) CADman wrote: > The answer comes out fine but I would like it to > round off to 2 decimal points. > The program takes a string then converts the string to a double > does the calculation then converts it back to a string. > > The answer comes out say 386.1567752 and I would like the > answer to read 386.16 To which Mark McIntyre answered: > char str[10; > double z = 386.1567752; > sprintf(str, "%.2f", z); > > str now contains "386.16" and "Per 'Pedro' Olsson" answered: > double answer; > char output[40]; > > answer = 386.1567752; > sprintf( output, "%.2Lf", answer ); /* output = "386.16" */ and Igor Siemienowicz answered: > Use the 'sprintf' function to print to the string like this: > > char pszAnswer[20]; > sprintf(pszTemp, "%5.2f", nAnswer); > > Where 'nAnswer' is the result of your calculation. I'm curious about the number of wrong answers here. Obviously, the value given by the original poster is an example; if the real value were a constant, he could just use a string literal and be done with it. Given a variable, all of the above programs fail radically ; to see why, suppose that the variable happened to contain 1.23e300, instead of the example results. There is *NO* way to write a correct program using a "%f" format to sprintf without having restricted the range of the variable first. The correct answer is, of course: ostrstream s ; s.setf( ios::fixed , ios::floatfield ) ; s.precision( 2 ) ; s << value << ends ; // Use s.str(), perhaps by making a copy of it. s.rdbuf()->freeze( 0 ) ;