954,496 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

'Double' decimal function problem.

Hi Daniweb!
I couldnt find my problem anywhere else on this forum, so I decided to make my own thread...

My problem: I'm trying to make a function to decide how many decimals a 'double' has.
My code (slightly edited, here's the base of it):

// int m = 0;

int decimal ( double total) {

double dec = total - (int) total;
if (dec)
  {
     m++
     dec *=10;
     decimal (dec);
  }
else
     return m;

}


The results: the funtion works, if there're no decimals. Else it returns my max, which is 5.

ANY help would be very aprreciated!
Thanks in advance

hiddepolen
Posting Whiz in Training
297 posts since Oct 2010
Reputation Points: 82
Solved Threads: 35
 

this is an idea I had. remove everything above 0 like you did. then convert the decimal bit to a string. then get the length of the string.

#include <iostream>
#include <string>
#include <sstream>

int DecimalPlaces(double test)
{
	double JustDecimals = test - (int) test;

	std::stringstream converter;

	converter<< JustDecimals;

	std::string StringForm(converter.str());

	return StringForm.length() - 2 /* -2 characters for the 0. */;

}

int main()
{
	std::cout<< "decimal places in " << 0.235987 << " " << DecimalPlaces(0.235987);
        // returns 6 which is right
}


this works but it does not test exceptions like if the input is not a decimal then dont minus the 2 otherwise DecimalPlaces(3) == -2

oh and the maximum number of decimal places seems to be 6 (with one number to the left of the decimal point).

MattyRobot
Junior Poster in Training
73 posts since Aug 2009
Reputation Points: 33
Solved Threads: 8
 

Thanks a lot!

I wouldn't have come up with this solution =-)
I'll test if this works when I'm home, and mark the thread solved.

(The max of 6 decimals doesn't matter, only 5 are needed. )

hiddepolen
Posting Whiz in Training
297 posts since Oct 2010
Reputation Points: 82
Solved Threads: 35
 

Thanks, it works great.

Ive put a 'if', so that if there are 0 decimals, it will just return 0.

int DecimalPlaces(double test)
{
	double JustDecimals = test - (int) test;
	if (!JustDecimals)
		return 0;
	std::stringstream converter;

	converter<< JustDecimals;

	std::string StringForm(converter.str());

	return StringForm.length() - 2 /* -2 characters for the 0. */;

}
hiddepolen
Posting Whiz in Training
297 posts since Oct 2010
Reputation Points: 82
Solved Threads: 35
 

pleased I could help :)

MattyRobot
Junior Poster in Training
73 posts since Aug 2009
Reputation Points: 33
Solved Threads: 8
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: