template<typename ValueType>
std::string ConvertToString(ValueType value)
{
std::stringstream ss;
ss << value;
return ss.str();
}
With the above code snippet, I am able to
use
str = ConvertToString<DWORD>(temp1);
to obtain a decent string for DWORD numbers.
But it did not succeed with floats
with a number of predefined significant digits.
This is what I wanted to obtain, say,
0.0000001
But the function returns
-3e-006
In normal circumstances, we do
sprintf (buff, "%.6f", number);
How can I turn the above function
into a generic function which can accept
floating point numbers in anyway I want?
Thanks
Jack
Furthermore a decimal constant is by default double not float. To make
it float you mas append f to it's end.
This is how I would do it:
#include <string>
#include <sstream>
#include <iomanip>
template<typename charT, typename ValueType>
std::basic_string<charT> ConvertToString(ValueType value)
{
std::basic_stringstream<charT> ss;
ss << value;
return ss.str();
}
template<typename charT>
std::basic_string<charT> ConvertToString(float value)
{
std::basic_stringstream<charT> ss;
ss << std::fixed << std::setprecision(8) << value;
return ss.str();
}
template<typename charT>
std::basic_string<charT> ConvertToString(double value)
{
std::basic_stringstream<charT> ss;
ss << std::fixed << std::setprecision(10) << value;
return ss.str();
}
And the usage
std::cout << ConvertToString<char>(0.0000001f) << std::endl;
if you are open to using boost look into lexical_cast
std::string b = boost::lexical_cast<std::string>( 10.456 );
double d = boost::lexical_cast<double>(b);
It does not allow for formatting, so you will get maximum precision
when casting floating point to string.
I tried that on my VS 2005 and everything works fine. Can you show your
code?