Skip to content

Instantly share code, notes, and snippets.

@rdtr
Last active August 29, 2015 14:10
Show Gist options
  • Save rdtr/1812d889fa34a2058782 to your computer and use it in GitHub Desktop.
Save rdtr/1812d889fa34a2058782 to your computer and use it in GitHub Desktop.
C++: Formatting float to string with arbitrary decimal digits
std::stringstream ss;
// set a flag to formatting with decimal digits
ss.setf(std::ios_base::fixed, std::ios_base::floatfield);
float f = 1.555555;
// set a nuber of digits
ss.precision(2);
ss << "Float: " <<f;
printf("%s\n", ss.str().c_str()); // "Float: 1.55"
// reset a flag
ss.setf(std::ios_base::fmtflags(0), std::ios_base::floatfield);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment