C/C++ counting the number of decimals?

Two ways I know of, neither very clever unfortunately but this is more a limitation of the environment rather than me 🙂

The first is to sprintf the number to a big buffer with a "%.50f" format string, strip off the trailing zeros then count the characters after the decimal point. This will be limited by the printf family itself. Or you could use the string as input by the user (rather than sprintfing a floating point value), so as to avoid floating point problems altogether.

The second is to subtract the integer portion then iteratively multiply by 10 and again subtract the integer portion until you get zero. This is limited by the limits of computer representation of floating point numbers – at each stage you may get the problem of a number that cannot be represented exactly (so .2155 may actually be .215499999998). Something like the following (untested, except in my head, which is about on par with a COMX-35):

count = 0
num = abs(num)
num = num - int(num)
while num != 0:
    num = num * 10
    count = count + 1
    num = num - int(num)

If you know the sort of numbers you’ll get (e.g., they’ll all be 0 to 4 digits after the decimal point), you can use standard floating point “tricks” to do it properly. For example, instead of:

while num != 0:

use

while abs(num) >= 0.0000001:

Leave a Comment