I went through some code where the number of digits was determined by casting the numbers into a string, and then using len ().
Function numOfDigits_len(n As Long) As Long numOfDigits_len = Len(Str(n)) - 1 End Function
Now, although this works, I knew that it would be slow compared to any method that didn't use strings, so I wrote one that uses log ().
Function numOfDigits_log(n As Long) As Long numOfDigits_log = Int(Log(n) / Log(10)) + 1 End Function
Reduce the lead time by 1/2, which was great, but there was something strange in the particular case.
n numOfDigits_log(n) ===== ==================== 999 3 1000 3 1001 4
It will not handle 1000 correctly. I decided that this was due to floating point and rounding issues.
Function numOfDigits_loop(ByVal n As Long) As Long Do Until n = 0 n = n \ 10 numOfDigits_loop = numOfDigits_loop + 1 Loop End Function
I wrote this, which turned out to be ~ 10% slower, since the numbers got more than 10 ^ 6 and seem to become slower large with increasing n. Which is good if I was pragmatic, but I would like to find something more ideal.
Now my question is: is there a way to use the log () method exactly. I could do something like
Function numOfDigits_log(n As Long) As Long numOfDigits_log = Int(Log(n) / Log(10) + 0.000000001) + 1 End Function
But it seems very "hacked." Is there a better way that is faster or faster than the log () method? Note. I understand that such optimization is in many cases pointless, but now that I’ve come across this, I would like to “fix” it.