I need to calculate the number of decimal places for a float value, e.g.
1234.567 -> 3
2.1233 -> 4
4.2432 -> 4
My initial idea was:
number = 1234.567;
...
while (number - (int)number > 0.0)
{
// Count decimal places
...
number *= 10;
}
However, this causes problems with float precision in the while-condition. The only safe workaround would be a conversion from float to string and then do string-based counting of decimal places.
The problem is: I must NOT use any libraries, neither third party nor C++ standard libraries (due to environmental restrictions). I know how to operate on a char* later on, but how can I convert my float value to a string (i.e. char*) without using C++ libraries?
Any help is greatly appreciated.
// Edit: This is my current approach, which still does not work (e.g. for 2.55555). How do I choose a proper threshold?
float abs(float number)
{
return (number > 0.0 ? number : number * -1);
}
int round(float number)
{
return (int)(number + 0.5);
}
void splitFloat(float* number, int* mantissa, int* exponent)
{
while (abs(*number - round(*number)) > 0.00001)
{
// *number -= (int)*number; // ???
*number *= 10.0;
*mantissa = *number;
*exponent += 1;
cout << "Number: " << *number << ", Mantisse: " << *mantissa << ", Exponent: " << *exponent << endl;
}
}
Your initial idea is pretty close, the problem is that floating point does rounding that keeps the result from being exact. You need to use a threshold instead of comparing to exactly 0.0, and you need to allow that the (int)
operation might truncate incorrectly and you should round instead. You can round by adding 0.5 before truncating.
You'll also run into a problem when the number of digits doesn't fit into an int
anymore. You can help by subtracting off the integer part of the number at each step.
Edit: To choose a proper threshold, pick the maximum number of decimals you want to process. If that's 4, then the smallest number you want to output is 0.0001
. Make your threshold half of that, or 0.00005
. Now, every time you multiply your number by 10, multiply the threshold by 10 too!
float threshold = 0.00005;
while (abs(*number - round(*number)) > threshold)
{
*number *= 10.0;
threshold *= 10.0;
// ...
}
If your float and int are both 32 bits, you shouldn't have to worry about subtracting out the int. It would make it harder to return the mantissa as you're doing.
Also, a warning I meant to give you before but forgot: this only works for positive numbers.
One more warning, the range of values for a float
is quite limited. You might not be able to exactly represent 1234.5670
for example, and you'll get an extraneous digit on the end. Changing to double
would fix that.