Skip to content

Instantly share code, notes, and snippets.

@esmitt
Created April 23, 2021 15:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save esmitt/795291b30ce61d0dfd084bf9727b65d8 to your computer and use it in GitHub Desktop.
Save esmitt/795291b30ce61d0dfd084bf9727b65d8 to your computer and use it in GitHub Desktop.
A function to convert a numerical data type into a string using precision decimals
#include <iostream>
#include <string>
#include <sstream>
template <typename T>
std::string to_string_with_precision(const T a_value, const int n = 4)
{
std::ostringstream out;
out.precision(n);
out << std::fixed << a_value;
return out.str();
}
int main()
{
std::cout<<to_string_with_precision(3.1452343424) << std::endl;
std::cout<<to_string_with_precision(3.1090f) << std::endl;
std::cout<<to_string_with_precision(3) << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment