Is there an algorithm to count digits of a decimal number other than saving it as a string and then looping to find the decimal point and thus count the digits?
8
I know what you are thinking. You are thinking that if you could somehow enumerate the digits after the decimal point, you could count them. But whether you use a string or any other mechanism, there is a fundamental problem:
how do you know when to stop counting?
Converting the number to a string might sound like an easy solution, but that’s only because someone else has already made this fundamental decision for you, and their choice has a rather slim chance of being the right choice for you. If you ask for a string representation of π
(happy π
day, by the way!) you will obviously get a finite length string, which might tempt you to believe that π
has a finite number of digits.
Not.
So, what you are trying to do will not work, because there are many numbers that cannot be accurately represented using either floats or doubles, so such numbers appear to contain meaningless decimal digits which only end there where the precision of the float or double ends. Please do try this at home: printf( "%.30fn", 2.9f );
the result will be something funny, like 2.900000095367431640625000000000
or 2.899999999999999911182158029987
, or similar depending on your machine and compiler.
And of course, this will easily manifest itself in calculations: if you divide 29
by 10
you will not really get 2.9
, but an approximation of it.
So, whatever you think you are going to accomplish by counting the decimal digits of a number will not work. You have some other kind of problem to solve, and you think that counting decimal digits will solve it, and you have come here to ask us how to implement your imaginary solution. This is a typical instance of asking an answer instead of asking a question. It is nothing to be ashamed of, lots of people make this mistake on stack exchange, but my point here is that you better find a way to solve your original problem which does not involve counting the decimal digits of a number.
2
You have options:
- Take the absolute value of the number, now it is positive.
- Then turn it into a string.
- Then find the “.” by searching for the “.” by using a string function or by looking one character at a time.
Or you can try:
- Take the absolute value of the number.
- Use the log function, which might be in a math library. You don’t want the natural log, you want the base ten version of a log.
- Truncate the answer from the log and add 1. Now you have the number of chars to the left of the decimal point.
or you can try:
- Take the absolute value of the number.
- Truncate the number. This throw away everything to the right.
- Turn the result into a sting
- get the length of the string.
which is faster? which is easier to understand?
Try one, make test cases, time it; then move to the next one.
Research why taking the absolute value is important.