Created
April 23, 2021 15:03
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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