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;
}
}