I'm working on a function to compute the number of decimal places in a variable. It works fine some of the time, but other times it behaves unpredictably. I read that this is due to a double representation error but I don't fully understand what the person was telling me.
Here is the simple function:
1 2 3 4 5 6 7 8 9 10
int f_Decimals(double num) {
int i = 0;
while (fmod(num, floor(num))) {
cout << i << ": " << fmod(num, floor(num)) << "\n";
i++;
num = num * 10;
}
return i;
}
For example, if I pass the number 1.233256 to the function, fmod(num, floor(num)) becomes the following values in sequence:
Other numbers work fine. Clearly the fmod function is returning a value close to 1 when it tried to fmod(6.0, 6.0). Any help as to how to fix this problem and have the function compute the proper number of decimal places would be appreciated.
The point is, I'm trying to make a function that rounds a double value to an arbitrary level of decimal precision. I assume I'm having trouble because of base-8 and base-10 differences. Is there something that can help me achieve my desired effect? Here's the round function I'm working on... bear in mind I've been programming for a week, so it's probably not pretty.
Rounding to an arbitrary precision and displaying the digits correctly are entirely different problems.
Due to base 2 <-> base 10 conversion problems, it's very unlikely that the stored value will be exactly the one you wanted. But that's generally not a problem because the error will be very small.
In your example, the error was of the order of 10^{-10}. Is that really a problem ?