yogi_bear_79 wrote:
I have a double of unknown length that I need to split at the
decimal. I thought I would convert it either to a string or a char.
char seems to be the best since it easily lends itself to splitting.
I have a few issues with this theory. Hard codeing char M[6] works
fine for my test double -0.5 But I would like it to be more
versitile. The format "%2.2f" works fine with my test data, but that
should also be versitile.
inline void LineSegment::perpBisect(const double m, const Point p)
char M[6] ;
sprintf(M,"%2.2f",m);
Here is a way using stringstream. Depending on what you need to do with the
parts depends on how you would optimize it if necessary.
Output is:
Whole Number: 1 Fraction: 2345
Whole Number: 2 Fraction: 0
Whole Number: 0 Fraction: 333333
#include <string>
#include <sstream>
#include <iostream>
void ShowDouble( const double& Value )
{
std::stringstream Stream;
Stream << Value;
std::string Digits;
Stream >Digits;
std::string::size_type Pos = Digits.find('.');
std::string WholeNumber;
std::string Fraction;
if ( Pos == std::string::npos )
{
WholeNumber = Digits;
Fraction = "0";
}
else
{
WholeNumber = Digits.substr( 0, Pos );
Fraction = Digits.substr( Pos + 1 );
}
std::cout << "Whole Number: " << WholeNumber << " Fraction: " <<
Fraction << "\n";
}
int main()
{
ShowDouble( 1.2345 );
ShowDouble( 2 );
ShowDouble( 1.0 / 3 );
}
--
Jim Langston
ta*******@rocketmail.com