Lets say that input from the user is a decimal number, ex. 5.2155 (having 4 decimal digits). It can be stored freely (int,double) etc.
Is there any
This is a robust C++ 11 implementation suitable for float and double types:
#include
#include
#include
template
std::enable_if_t<(std::is_floating_point::value), std::size_t>
decimal_places(T v)
{
std::size_t count = 0;
v = std::abs(v);
auto c = v - std::floor(v);
T factor = 10;
while (c > 0 && count < std::numeric_limits::max_digits10)
{
c = v * factor;
c = c - std::floor(c);
factor *= 10;
count++;
}
return count;
}
It throws the value away each iteration and instead keeps track of a power of 10 multiplier to avoid rounding issues building up.