[Haskell-cafe] How to calculate de number of digits of an
integer? (was: Is logBase right?)
ekirpichov at gmail.com
Sat Aug 22 13:34:32 EDT 2009
Ouch, my bad. length.show is better :)
2009/8/22 Derek Elkins <derek.a.elkins at gmail.com>:
> 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]
> round won't work because 999 is close to 1000.
> You simply need to use logBase 10 as a guess and then check the answer, e.g.
> numDigits n | n < n' = e
> | otherwise = e + 1
> where e = ceiling $ logBase 10 $ fromIntegral n
> n' = 10^e
> This will need to special case 0 which it currently doesn't do.
Web IR developer, market.yandex.ru
More information about the Haskell-Cafe