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

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).

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. )

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. */;

}

pleased I could help :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.