Using stringstream to print a rounded floating point number

i have floating point variables "lmin" and "lmax". I want to display only 4 significant digits. I am currently using what I found online in the form ...

string textout; stringstream ss; ss << lmin; textout = ss.str(); output(-0.5, -0.875, textout); ss.str(""); ss << lmax; textout = ss.str(); output(0.2, -0.875, textout); 

where "output" is just a function that I wrote to parse a string and print it on the screen. the important point is how do I print only the ROUNDED version of lmin and lmax for ss?

+6
source share
2 answers

Use std::setprecision to indicate the number of digits after the decimal point.

 #include <sstream> #include <iostream> #include <iomanip> int main() { double d = 12.3456789; std::stringstream ss; ss << std::fixed << std::setprecision( 4 ) << d; std::cout << ss.str() << std::endl; } 

Conclusion:

 12.3457 
+11
source

Just use ss.precision( 4 ) or ss << std::setprecision( 4 ) before inserting the output.

+1
source

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


All Articles