"Pretty" lexical_cast
Hello!
I want to create a "pretty" lexical_cast, that formats numbers by rounding
them slightly. For example, the number 68.61893 is converted to
68.61893000000001 by lexical_cast to string. Likewise, the number 72.947251
is converted to 72.94725099999999. Is there a way to add or subtract a
small value before conversion, to get what I want? Here's my (failed)
attempt:
#include <boost/lexical_cast.hpp>
#include <limits>
using namespace boost;
using namespace std;
template<class T>
T pretty_lexical_cast(double x)
{
T s = lexical_cast<T>(x);
// I'm not sure what value to add/subtract here
T s_p = lexical_cast<T>(x + numeric_limits<double>::epsilon());
T s_m = lexical_cast<T>(x - numeric_limits<double>::epsilon());
// return string with smallest number of characters
if( s.size() < s_p.size() )
{
if( s.size() < s_m.size() )
return s;
else
return s_m;
}
else if( s_p.size() < s_m.size() )
return s_p;
else
return s_m;
}
int main()
{
{
double x = 72.947251;
string s = pretty_lexical_cast<string>(x);
}
{
double x = 68.61893;
string s = pretty_lexical_cast<string>(x);
}
}
Any help much appreciated.
Thanks in advance!
--
Daniel
A: Because it messes up the order in which people normally read text.
Q: Why is top-posting such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?