# [Haskell-cafe] How to calculate de number of digits of an integer? (was: Is logBase right?)

Eugene Kirpichov ekirpichov at gmail.com
Sat Aug 22 13:25:37 EDT 2009

```Or better numDigits = length . show
It's probably even faster.

2009/8/22 Eugene Kirpichov <ekirpichov at gmail.com>:
> Use 'round' instead of 'truncate'.
>
> Prelude> let numDigits = (+1) . round . logBase 10 . fromIntegral
> Prelude> map (numDigits . (10^)) [0..9]
> [1,2,3,4,5,6,7,8,9,10]
>
> 2009/8/22 Roberto López <plastermoso at hotmail.com>:
>> Ok. I wonder if someone could help me with this problem...
>>
>> I want to calculate the number of digits of a positive integer. I was
>> thinking of ...
>>
>>        numDigits n = truncate (logBase 10 n) + 1
>>
>> But (logBase 10 1000) = 2.9999999999999996 so numDigits 1000 = 2.
>>
>> Maybe adding a small amount
>>
>>        numDigits n = truncate ((logBase 10 n) + 0.0000000000000005) + 1
>>
>> Prelude> numDigits 100
>> 3
>> Prelude> numDigits 1000
>> 4
>> Prelude> numDigits 10000
>> 5
>> Prelude> numDigits 10000
>> 5
>> Prelude> numDigits 100000
>> 6
>> Prelude> numDigits 1000000
>> 7
>> Prelude> numDigits 10000000
>> 8
>> Prelude> numDigits 100000000
>> 9
>> Prelude> numDigits 1000000000
>> 9                                          <---- This is wrong!!!!
>> Prelude> numDigits 10000000000
>> 11
>>
>> Is there a reliable way to calculate the number of digits by means of
>> logBase?
>>
>>
>> Regards!
>>
>> _______________________________________________
>>
>
>
>
> --
> Eugene Kirpichov
> Web IR developer, market.yandex.ru
>

--
Eugene Kirpichov
Web IR developer, market.yandex.ru
```