1

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;  
  }  
}
K DawG
  • 13,287
  • 9
  • 35
  • 66
  • 4
    What you are trying to do doesn't really make any sense. Whatever your outer problem is, this is probably not a sensible way to solve it. – David Schwartz Mar 23 '12 at 17:45
  • 3
    possible duplicate of [How to convert strings to floats with perfect accuracy?](http://stackoverflow.com/questions/2174012/how-to-convert-strings-to-floats-with-perfect-accuracy) – Jon Mar 23 '12 at 17:46
  • If you aren't using the C++ standard library then you're pretty much just writing C, ignoring many useful features. – Mark B Mar 23 '12 at 17:47
  • @Jon's link is for a question using `D` but the answers are not contrained to that languge. – madth3 Mar 23 '12 at 17:49
  • @madth3: ...which is why I think this is a legitimate dupe. – Jon Mar 23 '12 at 17:50
  • @Jon, isn't that question going the opposite direction? This is float to string, not string to float. – Mark Ransom Mar 23 '12 at 17:55
  • A little bit of background would be appreciated. Is this a homework question? Are you trying to do something specific? is it absolutely mandatory that you use a float, or are you using the float because that's what you expect to use? This seems overly complicated, and I suspect there must be a better way to do what you want to do ... – Marc Reside Mar 23 '12 at 18:00
  • @Marc Reside: Use of float is mandatory. Aim is to normalize the float value and then get it's mantissa and exponent as integer values. Restriction is that no libraries must be used, due to environmental limitations. –  Mar 23 '12 at 18:45

3 Answers3

5

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.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • Your idea of adding 0.5 before truncating sounds interesting, I'll give it a try. However, can you please clarify "subtracting off the integer part of the number at each step"? Maybe with a code example? Thanks. –  Mar 23 '12 at 19:02
  • @Buxme, it's easy - sometime before `number *= 10` do `number -= (int)number` so that all you're left with are the digits to the right of the decimal. – Mark Ransom Mar 23 '12 at 19:31
  • I tried to incorporate your ideas with my code (see initial post), but it's still far from functioning. The rounding seems to work fine, but I'm still having troubles with choosing a proper threshold. –  Mar 25 '12 at 18:49
  • @Buxme, I don't know if StackOverflow notifies you when an answer is edited so I'm telling you - I answered your comment in my answer. – Mark Ransom Mar 26 '12 at 17:23
  • Saw that already, thanks. Multiplying the threshold as well, did the trick. However the code is still kind of unsafe. It works for 2.55555 now, but the more fractional digits I have, the more likely it is to fail again. But I understand that this is a problem with float precision in C++ and not with your solution, which I will mark as accepted this way. –  Mar 26 '12 at 19:05
  • I don't quite understand why the loop rounds instead of truncating. Is there a reason for this? Truncating makes more sense to me. – celticminstrel Sep 06 '22 at 15:19
  • 1
    @celticminstrel the problem is that floating point operations like `*= 10.0` don't always give exact results, see [Is floating point math broken?](https://stackoverflow.com/q/588004/5987) Truncation might give you a result that's 0.999999 off, rounding prevents that from being a problem. – Mark Ransom Sep 06 '22 at 18:09
1

Your original idea is good, but you need to assume a minimum error:

number = 1234.567;
...
while (fabs(number - round(number) > 0.00001)
{
    // Count decimal places
    ...
   number *= 10;
}

Note that when you say 1234.567 the computer may say 1234.5670000001 or 1234.566999999 and you do not want to count all that buch of 0s or 9s.

And beware of the ronding, instead of the truncation!

But note that it may not work as expected with negative numbers.

rodrigo
  • 94,151
  • 12
  • 143
  • 190
  • This fails when binary rounding places the number just below the integer representation rather than just above. – Mark Ransom Mar 23 '12 at 17:56
  • @MarkRansom - Right! you have to round, as you say in your simultaneous answer. Corrected – rodrigo Mar 23 '12 at 17:58
  • @rodrigo: I am aware of the problem with float precision (see my initial post) and have read about using a threshold before. But what would be a good minimum error to assume? Furthermore I cannot use any includes like cmath. –  Mar 23 '12 at 18:55
0

I'd think you'd best off to compute std::numeric_limits<float>::digits10 - log10(value) as this is the maximum of decimal digits the value will have. If you have something to format the number you can format to this precision and strip off trailing zeros. If don't have something to format the value you'll have a lot of doing it probably: the approach is distinctly non-trivial if you want good results.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
  • Unfortunately there is no std or log10() in the environment, I'm bound to. –  Mar 23 '12 at 18:47
  • Well, the number of decimal digits in a `float` won't change between platforms using the same architecture. The well-guarded, secret value happens to be 7 (IEEE-754 32 bit binary floating point number). ... and actually `log10(value + 1)` is just a posh way to call the the number of decimal integral numbers in `value` (I had forgotten the 1, though). This isn't really rocket science to compute. – Dietmar Kühl Mar 23 '12 at 19:21